Javascript как изменить стиль css для элемента
Перейти к содержимому

Javascript как изменить стиль css для элемента

  • автор:

Стили и классы

До того, как начнёте изучать способы работы со стилями и классами в JavaScript, есть одно важное правило. Надеемся, это достаточно очевидно, но мы всё равно должны об этом упомянуть.

Как правило, существует два способа задания стилей для элемента:

  1. Создать класс в CSS и использовать его: <div >
  2. Писать стили непосредственно в атрибуте style : <div style=". "> .

JavaScript может менять и классы, и свойство style .

Классы – всегда предпочтительный вариант по сравнению со style . Мы должны манипулировать свойством style только в том случае, если классы «не могут справиться».

Например, использование style является приемлемым, если мы вычисляем координаты элемента динамически и хотим установить их из JavaScript:

В других случаях, например, чтобы сделать текст красным, добавить значок фона – описываем это в CSS и добавляем класс (JavaScript может это сделать). Это более гибкое и лёгкое в поддержке решение.

className и classList

Изменение класса является одним из наиболее часто используемых действий в скриптах.

Когда-то давно в JavaScript существовало ограничение: зарезервированное слово типа "class" не могло быть свойством объекта. Это ограничение сейчас отсутствует, но в то время было невозможно иметь свойство elem.class .

Поэтому для классов было введено схожее свойство "className" : elem.className соответствует атрибуту "class" .

Если мы присваиваем что-то elem.className , то это заменяет всю строку с классами. Иногда это то, что нам нужно, но часто мы хотим добавить/удалить один класс.

Для этого есть другое свойство: elem.classList .

elem.classList – это специальный объект с методами для добавления/удаления одного класса.

Так что мы можем работать как со строкой полного класса, используя className , так и с отдельными классами, используя classList . Выбираем тот вариант, который нам удобнее.

  • elem.classList.add/remove("class") – добавить/удалить класс.
  • elem.classList.toggle("class") – добавить класс, если его нет, иначе удалить.
  • elem.classList.contains("class") – проверка наличия класса, возвращает true/false .

Кроме того, classList является перебираемым, поэтому можно перечислить все классы при помощи for..of :

Element style

Свойство elem.style – это объект, который соответствует тому, что написано в атрибуте "style" . Установка стиля elem.style.width="100px" работает так же, как наличие в атрибуте style строки width:100px .

Для свойства из нескольких слов используется camelCase:

Стили с браузерным префиксом, например, -moz-border-radius , -webkit-border-radius преобразуются по тому же принципу: дефис означает заглавную букву.

Сброс стилей

Иногда нам нужно добавить свойство стиля, а потом, позже, убрать его.

Например, чтобы скрыть элемент, мы можем задать elem.style.display = "none" .

Затем мы можем удалить свойство style.display , чтобы вернуться к первоначальному состоянию. Вместо delete elem.style.display мы должны присвоить ему пустую строку: elem.style.display = "" .

Если мы установим в style.display пустую строку, то браузер применит CSS-классы и встроенные стили, как если бы такого свойства style.display вообще не было.

Обычно мы используем style.* для присвоения индивидуальных свойств стиля. Нельзя установить список стилей как, например, div.style="color: red; width: 100px" , потому что div.style – это объект, и он доступен только для чтения.

Для задания нескольких стилей в одной строке используется специальное свойство style.cssText :

Это свойство редко используется, потому что такое присваивание удаляет все существующие стили: оно не добавляет, а заменяет их. Можно ненароком удалить что-то нужное. Но его можно использовать, к примеру, для новых элементов, когда мы точно знаем, что не удалим существующий стиль.

То же самое можно сделать установкой атрибута: div.setAttribute(‘style’, ‘color: red. ‘) .

Следите за единицами измерения

Не забудьте добавить к значениям единицы измерения.

Например, мы должны устанавливать 10px , а не просто 10 в свойство elem.style.top . Иначе это не сработает:

Пожалуйста, обратите внимание, браузер «распаковывает» свойство style.margin в последних строках и выводит style.marginLeft и style.marginTop из него.

Вычисленные стили: getComputedStyle

Итак, изменить стиль очень просто. Но как его прочитать?

Например, мы хотим знать размер, отступы, цвет элемента. Как это сделать?

Свойство style оперирует только значением атрибута "style" , без учёта CSS-каскада.

Поэтому, используя elem.style , мы не можем прочитать ничего, что приходит из классов CSS.

Например, здесь style не может видеть отступы:

…Но что, если нам нужно, скажем, увеличить отступ на 20px ? Для начала нужно его текущее значение получить.

Для этого есть метод: getComputedStyle .

Результат вызова – объект со стилями, похожий на elem.style , но с учётом всех CSS-классов.

Есть две концепции в CSS:

  1. Вычисленное (computed) значение – это то, которое получено после применения всех CSS-правил и CSS-наследования. Например, height:1em или font-size:125% .
  2. Окончательное (resolved) значение – непосредственно применяемое к элементу. Значения 1em или 125% являются относительными. Браузер берёт вычисленное значение и делает все единицы измерения фиксированными и абсолютными, например, height:20px или font-size:16px . Для геометрических свойств разрешённые значения могут иметь плавающую точку, например, width:50.5px .

Давным-давно getComputedStyle был создан для получения вычисленных значений, но оказалось, что окончательные значения гораздо удобнее, и стандарт изменился.

Так что, в настоящее время getComputedStyle фактически возвращает окончательное значение свойства, для геометрии оно обычно в пикселях.

Для правильного получения значения нужно указать точное свойство. Например: paddingLeft , marginTop , borderTopWidth . При обращении к сокращённому: padding , margin , border – правильный результат не гарантируется.

Например, если есть свойства paddingLeft/paddingTop , то что мы получим вызывая getComputedStyle(elem).padding ? Ничего, или, может быть, «сгенерированное» значение из известных внутренних отступов? Стандарта для этого нет.

Посещённые ссылки могут быть окрашены с помощью псевдокласса :visited .

Но getComputedStyle не даёт доступ к этой информации, чтобы произвольная страница не могла определить, посещал ли пользователь ту или иную ссылку, проверив стили.

JavaScript не видит стили, применяемые с помощью :visited . Кроме того, в CSS есть ограничение, которое запрещает в целях безопасности применять к :visited CSS-стили, изменяющие геометрию элемента. Это гарантирует, что нет обходного пути для «злой» страницы проверить, была ли ссылка посещена и, следовательно, нарушить конфиденциальность.

Итого

Для управления классами существуют два DOM-свойства:

  • className – строковое значение, удобно для управления всем набором классов.
  • classList – объект с методами add/remove/toggle/contains , удобно для управления отдельными классами.

Чтобы изменить стили:

Свойство style является объектом со стилями в формате camelCase. Чтение и запись в него работают так же, как изменение соответствующих свойств в атрибуте "style" . Чтобы узнать, как добавить в него important и делать некоторые другие редкие вещи – смотрите документацию.

Свойство style.cssText соответствует всему атрибуту "style" , полной строке стилей.

Для чтения окончательных стилей (с учётом всех классов, после применения CSS и вычисления окончательных значений) используется:

  • Метод getComputedStyle(elem, [pseudo]) возвращает объект, похожий по формату на style . Только для чтения.

Задачи

Создать уведомление

Напишите функцию showNotification(options) , которая создаёт уведомление: <div > с заданным содержимым. Уведомление должно автоматически исчезнуть через 1,5 секунды.

Пример объекта options :

Используйте CSS-позиционирование для отображения элемента в заданных координатах. Исходный документ имеет необходимые стили.

Изменение стилей через JavaScript

Изменение стилей через JavaScript

Как правило, начинающие изучать веб-разработку люди уже знают, как легко можно поменять внешний вид элемента с помощью CSS стилей. Но менять стили можно и через JavaScript. Когда же наступает необходимость это делать через JavaScript? Первое, что приходит в голову — это для создании анимаций.

Изменение стилей через CSS

У нас есть черный заголовок в розовой рамке. За внешний вида заголовка отвечают CSS стили.

//CSS код
.container <
width: 400px;
border: 10px solid plum;
margin: 20px auto;
>

#heading <
font-size: 24px;
font-weight: 700;
color: black;
font-family: 'Arial Narrow Bold', sans-serif;
text-align: center;
>

Изменение стилей через JavaScript.

Если мы хотим изменит цвет у заголовка с черного на фиолетовый, то идем в CSS код и вручную заменяем значение у свойства color.

#heading <
color: violet;
>

Заголовок стал фиолетовый.

Изменение стилей через JavaScript.

Изменение стилей через JavaScript

Но мы хотим большего взаимодействия с пользователем. Чтобы цвет заголовка менялся вследствии наступления какого-нибудь события (клика мыши). Изменим наш заголовок на фиолетовый через JavaScript. Действуем уже по отработанному алгоритму:

  1. Получить элемент
  2. Обратится к свойству элемента
  3. Установит новое значение

Найдем заголовок по названию селектора и поместим его в переменную headingElement для дальнейших манипуляций. Затем получим доступ к его атрибуту style и укажем нужное нам свойство color, которое собираемся изменить. То есть, мы обращаемся к свойству color у стиля того элемента, который лежит а переменной headingElement и устанавливаем ему новое значение — фиолетовый цвет. В записи мы используем две точки, потому что у нас два объекта. Первый объект сам элемент h1, а второй объект — style, в свойствах которого хранятся все стили элемента h1.

// получение элемента по селектору
let headingElement = document.querySelector('#heading');
// обращение к интересующему свойству и присвоение нового цвета
headingElement.style.color = 'violet';

Цвет заголовка опять поменялся на фиолетовый.

Изменение стилей через JavaScript.

Названия свойств

Теперь попробуем изменить цвет рамки у заголовка. Действуем по аналогии с заменой цвета. Получаем элемент container, у которого будем менять цвет свойства border-color с розового на черный.

let containerElement = document.querySelector('.container');
containerElement.style.border-color = 'black'; // нельзя писать border-color

Упс! Ничего не произошло и выскочило сообщение об ошибке, а цвет у рамки не поменялся. Почему не сработало? Ведь в обычном CSS мы бы так и написали border-color: black. Все дело в дефисе, имена свойств в JavaScript не могут содержать дефис. Поэтому все CSS свойства в названиях которых есть дефис, нужно преобразовать в другой синтаксис. Для этого мы убираем дефис и пишем первую букву второго слова, заглавной. Такой стиль написания называется camelCase (верблюжий регистр), напоминающий горбы верблюда.

let containerElement = document.querySelector('.container');
containerElement.style.borderColor = «black»; // так правильно borderСolor

Теперь наш обновленный JavaScript сработал. Рамка у заголовка окрасилась в черный цвет.

Изменение стилей через JavaScript.

Заключение

Зачем вообще нужно изменять элементы на странице с помощью JavaScript? Не проще ли сразу создать HTML страницу с необходимым CSSкодом? Все дело в том, что JavaScript позволяет реагировать на события, производимые пользователем и менять CSS свойства прямо на ходу. Во взаимодействии с пользователем и заключается вся сила языка JavaScript. Например вы можете создавать формы и проверять, что туда вводит пользователь. Просто создавать HTML страницы и стилизовать их согласно макету заказчика, недостаточно в современной веб-разработке. Вы можете возразить, что для этого есть другие специалисты — JavaScript программисты. Однако в реальном мире, заказчики предпочитают выбирать исполнителей с опцией «все включено», чтобы цепочка исполнителей была, как можно короче. Поэтому изучайте JavaScript на моем видеокурсе, если вы хотите стать востребованным фронтенд-разработчиком.

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Порекомендуйте эту статью друзьям:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

Она выглядит вот так:

Комментарии ( 0 ):

Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

The JavaScript style API, and CSS values.

The JavaScript style API is one way to go about changing CSS values with a little javaScript code rather than just plain old static hard coded CSS. This is not to be confused with a javaScript coding style, which is of course a whole other subject that might be though of as another kind of javaScript style.

There are other ways of changing CSS values with javaScript such as changing the className property value of one or more elements with respect to a collection of hard coded CSS classes to work with. In some respects this might prove to be a better option, client side javaScript is not meant to be a replacement for HTML and CSS, if you are using javaScript to do everything in your site I would say that you might want to rethink your approach.

The style API is not the best choice for doing anything that might involve complex animations, or a great deal of rapid fast change, for those kinds of effects there are canvas elements, SVG, and CSS3 animations to work with all of which might prove to be better options. There are many tools to a web developer and the style API is not always the best tool for the job, but it is there, and in some cases the use of it may be called for. So lets take a look at the style API in javaScript today, and while I am at it I might touch base on a whole other little aspects of client side javaScript in general.

1 — JavaScript style API overview

I assume that you have at least some knowledge of how to work with javaScript in a front end environment, if not this is not a getting started post on javaScript let alone any of the subjects that are needed before hand. If you know at least the basics when it comes to adding script tags, and how to get references to an element, then you might be ready to learn a thing or two about the style API which can be a fun next step.

The style API is a property of an HTML element reference that serves as a way to intact with the in-line CSS style of that element via JavaScript code. This is a more dynamic way of controlling CSS rather than the use of the hard coded HTML style attribute of the element, or an external CSS file loaded into the page via a link element. This differs from any additional style rules that may apply to the element via class names, ids and other selectors in the CSS of a project.

In case you did not know style values set via the javaScript style API supersede all other style rules that may be in effect by way of hard coded CSS. This means that style API values will override CSS values that are defined by way of a style element, the in-line style attribute of an element, or an external CSS file. So in some cases where the style API is call for it can be used to overwrite anything that may be in effect via the hard coded CSS of a page.

— the source code examples here are on Github

The test vjs repository on my Guhub account is where I am parking the source code examples that I have slapped together for this post. In this repository I also have all the various other source code examples for my many other posts on client side javaScript. That repository would be a good place to make any and all pull requests that should be made, there is also the comments section at the bottom of this post that can be sued as a way to bring up some kind of problem that is relative to the style api in client side javaScript.

1.1 — Get in-line javaScript style

To get a style value that was set via the style attribute in the HTML element first I will need to get a reference to that element. One tired yet true way to do so is to use the document.getElementById method. There are many more modern alternatives to this method of course, however part of the appeal to working with the style API is that it will work in really old browsers, so it makes sense to stick to older methods of doing things as a way to make sure that things will still work.

In any case once there is a reference to the element that I want to set the style for I can use the style API to both get and set CSS rules. For example I can use the color property of the style API to get the current text color of an element.

So then the Style API can be used as a way to pul what the current style values are for a given element. Setting the style values for an element is not all that much harder.

1.2 — Set in-line javaScript style

Setting in-line style is just a matter of using the assignment operator with the desired property once a reference to the style API is obtained. There is some variation with the property names compared to the equivalent names that are used in hard coded css, but that is just about it.

So for the most part getting and setting CSS values is just a matter of getting a reference to an element to which one wants to mutate CSS values for, and then figure out what the property name is for the given CSS rule. The names are more or less the same only we are going with Camel case style with the names rather than dashes. That is about it when it comes to the basics of using the style API in client side javaScript. However maybe I should take a moment to cover at least a few more basic examples of this before moving on.

1.3 — Property names differ from CSS

As I mentioned before when setting the CSS property and value pairs for in-line style via the HTML style attribute, the property names are the same as they would be in a style element or external CSS file. However when accessing those values via the javaScript style API, the property names follow a camel case pattern.

SOe good examples of this would be background-color becoming backgroundColor, and z-index becoming zIndex;

2 — Get unknown in-line style values

So the CSS Style Declaration object that the style API is an instance of appears to have an array like nature to it when it comes to the styles that are set via the style attribute. In other words there is a collection of numbered rather than named key value pairs and a length property that is consistent with the way that arrays are structured in JavaScript. This means that an Array method like Array.forEach can be used to loop over any and all CSS properties that are set via the style attribute in the event that the set properties for an element are not known.

3 — A div grid example using the style API

One quick fun little project is to create a grid of div elements using the style API, and a few other client side javaScript Element methods and properties. When it comes to making a grid in client side javaScript there are many other alternatives such as canvas that might prove to be better solutions. However taking a moment to make one or two examples such as this might prove to be some good exercise when it comes to getting familiar with not just the style API, but other helpful methods and properties such as document.createElement, el.scrollWidth, and el.appendChild.

In this example I end up with a grid of div elements with random green colors for the background of each div element. Here I am setting some base style rules with a style element in the head of the HTML file. basically anything that will be fixed for the container element, as well as all the div elements should still be part of a set of static CSS rules.

However when creating div elements I do need to still set the class name that I want to use with each div element, and that can be done with the className property of the element object reference that is returned when using the cerateElement method. This can of course be used in conjunction with all the use case examples of the style API where I am setting values for width, height, top, and left on a per div bases.

There is a great deal more than can be done with an example such as this. If I get some time to expand this post more at some point in the future I think I will add a few more examples of this div grid thing when it comes to adding events and so forth.

4 — Moving divs example

In this example I will be creating a main app loop function using the request animation frame method to do so. In the main javaScript file that contains this main app loop I also have two helper methods that are used to cerate a collection of child divs for a given parent div, and one to update such a collection of elements for a parent div. It is in the update method that I am using the style api as a way to update the position of the dive elements.

4.1 — A main.js javaScript file with a app loop

Here I have the source code for the main javaScript file where I am using the style api to update the position of div elements. In the create element I am using the create element method of the document object as a way to go about creating some div elements by way of javaScript code and then I am appending them to the given parent element. In this method I am also setting some values for each div by way of the data attribute of each div element for the current position of the dive as well as speed heading and rate of change for heading.

4.2 — The html file and css

I just need a little HTML now in order to pull all of this together, which will also include a little base CSS for divs, as well as the two classes of divs.

5 — Conclusion

The javaScript style API might be fun to play with when it comes to just making quick examples that make use of the style API to move elements around the page. However when it comes to doing anything flashy there are better options for doing so such as the canvas element and also there is SVG that might also prove to be a better solution for anything that is going to be a bit animated.

There is also knowing when not to make things so flashy also though. I would say that it is generally a good idea to avoid making anything that is just eye candy when it comes to making any kind of serious application. Also when it comes to making a Game or anything where I would say doing a thing or two that is a little flashy is called for, the style API is just not such a great way to go about doing it.

Still the style API is there when it is needed. If for some reason I do want to set CSS values with javaScript it is the way to go about doing it. I just think that it is generally something that should be avoided when and where possible, and other alternatives should be explored.

How To Change CSS With JavaScript [With Examples]

JavaScript is all about dynamic stuff and dealing with dynamic CSS changes is just one of the scenarios where JavaScript is exactly what we need.

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

How To Modify CSS With JavaScript - Best Ways

Let’s get into the different ways we can do achieve this:

1. Change CSS inline properties with JavaScript

Setting individual styles directly from JavaScript is one of the most common scenarios when dealing with dynamic CSS styles.

This way allows you to change the CSS styles for one or multiple elements present in the DOM.

All you have to do is:

  1. Query the element present in the DOM.
  2. And set the style or styles for it one by one.

Notice that when setting the CSS styles using the style property you have to write the CSS properties in camelcase. Instead of using a dash — to separate the words you will have to write in capitals the first letter of each word. ( backgroundColor , fontSize )

If you execute this code just like this, you’ll notice the change takes place on page load.

If you want to change the CSS styles dynamically you’ll have to attach this portion of code to some event.

For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.

Here’s an example:

Note that when you apply specific styles using JavaScript, these styles have precedence over the styles applied externally on a stylesheet and even to the ones applied inline, in the HTML element itself.

In this case, for instance, we have an element with an inline style providing it with a yellow background.

If we now set the CSS color property to green using JavaScript, then our element will get a green color. It will overwrite the inline style and the style applied on the external CSS stylesheet.

2. Set Multiple CSS Styles At The Same Time

Imagine you have to apply, let’s say 5 or 10 styles for a single element.

You can go one by one and have something like the following:

But perhaps you are looking for a "smarter" way to change them all at the same time without so much code repetition.

If that’s the case, then I have good news for you!

You can actually pass a string value to the cssText property to set multiple CSS styles at once.

Even better, we can use template literals kind of strings to keep them separate in different lines as you do in your stylesheets.

If you are getting into JavaScript you might want to check our list with the Best Books To Learn JavaScript or What’s The Best Way To Learn JavaScript.

2. Change CSS class in JavaScript

In the same way, you can also remove certain classes by using classList.remove or even toggle them when using classList.toggle .

Here’s an example:

3. Change CSS stylesheets dynamically

Let’s say that now you do not want to add inline styles to an element or apply a class to it. Instead, you want to apply a change at the stylesheet level. Why?

There are a couple of reasons:

You might want to apply the change to all elements with a certain selector. But not just to the elements present right now on the HTML, but also to all future ones that will be added dynamically later on.

There might be a huge amount of elements sharing the selector you want to apply changes to. Imagine 500 elements sharing your selector, or even 1K, 5K, 10K. Having to select all those elements using JavaScript and then loop through them to change their style (or add a class) will be EXTREMELY slow.

Here’s where modifying the CSS stylesheet directly will come on handy.

You can select the stylesheets of a document by using document.styleSheets . If you know that the stylesheet you want to modify is the second one, you can get it by using document.styleSheets[2] .

Then, you would loop through all its rules and get the one you need to modify. In this case, if you want to modify the .element class, you can compare each of the rules’ selector with .element .

And here is the Codepen example that you can play with:

4. Append And Remove CSS stylesheets dynamically

In some cases, we might want to just append a whole new stylesheet or even replace an existing one.

The reason for it might be:

You have a web application that supports multiple themes and allows the user to change them dynamically.

You might want to package a component in a single JS file instead of having to include both files, the JS and the CSS one.

The way this works is quite simple:

  1. 1- We write the content for our new stylesheet using template literals.
  2. 2- We select the head element of the page to append our new stylesheet.
  3. 3- We create a stylesheet element using document.createElement("style")
  4. 4- We append our stylesheet content to the new style element by using document.createTextNode and appendChild .

And here is the Codepen example so you can test it by yourself and modify a few things to your needs:

5. Overwrite CSS !important style with JavaScript

We all know the rule: "Avoid using !important". But hey! Sometimes it’s really necessary or it is just out of our control.

The !important priority property makes sure that such style will be overwriting any inline declared style (written in the HTML element itself) as well as any previously declared rule that applies to your element.

So. what if we need to overwrite the style that was previously declared using !important ?

Imagine we have our element:

And the stylesheet using the !important rule like so:

All you have to do is apply the priority parameter on the setProperty function that JavaScript provides us:

Here’s an example:

Notice how when using setProperty we specify the CSS properties exactly in the same way we do in our stylesheet. Using a dash — to separate the words. ( background-color , font-size )

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *