Javascript добавить css стиль

How to set CSS styles using JavaScript

In my previous article, we looked at different ways to get style information from an HTML element using JavaScript. Today, you’ll learn how to apply CSS styles to HTML elements with JavaScript.

Let us say we have the following element:

div class="pizza">Hot, spicy, pizza 🍕div> 

Now, we want to change its text, background colors, and font style CSS properties using JavaScript. What should we do? There are multiple options available in JavaScript.

The easiest and straightforward way to change the CSS styles of an element with JavaScript is by using the DOM style property. All you need to do is fetch the element from DOM and change its inline styles:

const pizza = document.querySelector('.pizza') // change the text color to white pizza.style.color = 'white' // set background color to blue pizza.style.backgroundColor = 'blue' // change font style to italic pizza.style.fontStyle = 'italic' 

The style property uses the camel-case naming conventions for CSS properties and applies styles inline to the element:

div class="pizza" style="color: white; background-color: blue; font-style: italic;">Hot, spicy, pizza 🍕div> 

Another way is to create a

const style = document.createElement('style') 

Finally, append the style element to the DOM. To do this, get the tag using document.head , and then call the appendChild() method on it to append the style element:

document.head.appendChild(style) 
// create an element const style = document.createElement('style') // add CSS styles style.innerHTML = ` .pizza ` // append to DOM document.head.appendChild(style) 

The CSS Object Model is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify [the] CSS style dynamically.

The CSSStyleSheet.insertRule() method inserts a new CSS rule to a stylesheet. Here is how you can use this method to add styles to the above HTML element:

// create an new style const style = document.createElement('style') // append to DOM document.head.appendChild(style) // insert CSS Rule style.sheet.insertRule(` .pizza `) 

It is not really required to create a new element. You can use existing elements as well as external stylesheets to add CSS rules using insertRule() . The insertRule() method works in all modern browsers, including Internet Explorer 9 and higher.

Constructable Stylesheets is a modern way of creating and distributing reusable styles when working with the Shadow DOM. Here is an example that creates a Constructable Stylesheets and appends it to the Shadow DOM:

// create a new shared stylesheet const sheet = new CSSStyleSheet() // add CSS styles sheet.replaceSync(` .pizza `) // apply the stylesheet to a document document.adoptedStyleSheets = [sheet] 

In this article, we looked at four ways to add CSS styles to an HTML element in JavaScript. So, which method should you use? It depends on what you want to achieve by dynamically changing the CSS. If you only want to modify CSS styles for a single element, it is better to use the style property. This property changes the inline styles for a specific HTML element without affecting global styles. If you want to apply a style to a set of HTML elements, create a new tag with the necessary CSS properties and append it to the document. Read Next: How to add multiple CSS styles using JavaScript ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

.style

Свойство style получает и устанавливает инлайновые стили элемента, то есть те, что записываются через HTML-атрибут style .

С помощью него можно управлять стилем элемента. Специфичность этого свойства такая же, как у атрибута style .

Как пишется

Скопировать ссылку "Как пишется" Скопировано

Чтобы получить значения инлайновых стилей с помощью свойства style , мы можем записать:

 const element = document.getElementById('someElement')const inlineStyles = element.style const element = document.getElementById('someElement') const inlineStyles = element.style      

В этом случае в значение inline Styles запишется объект CSS Style Declaration , который будет содержать в себе все инлайновые стили элемента element .

Чтобы задать стили для элемента, мы можем использовать несколько способов. Либо через css Text , чтобы указать несколько свойств разом. (Тем же эффектом обладает установка стиля через set Attribute ( ) .) Либо через отдельные свойства в style . [ property Name ] .

Следующие две записи работают одинаково и устанавливают несколько стилей в одном выражении:

 element.style.cssText = 'color: blue; border: 1px solid black'element.setAttribute('style', 'color:red; border: 1px solid blue;') element.style.cssText = 'color: blue; border: 1px solid black' element.setAttribute('style', 'color:red; border: 1px solid blue;')      

Следующая — устанавливает значение определённого свойства, оставляя другие значения стиля нетронутыми:

 element.style.color = 'blue' element.style.color = 'blue'      

Как понять

Скопировать ссылку "Как понять" Скопировано

Свойство style — это механизм для работы со стилями на элементе. С его помощью можно управлять отображением элементов в «рантайме», то есть во время выполнения скрипта.

Этот механизм позволяет «перетирать» стили, описанные в CSS-таблицах, так как специфичность стилей в атрибуте style выше (за исключением стилей с !important ).

Чтобы указать значение конкретного CSS-свойства, мы можем использовать одноимённое отображение в style :

 // Если мы хотим указать color:element.style.color = 'red' // или 'rgb(255,0,0)', или '#f00' // Если хотим указать font-family:element.style.fontFamily = 'Arial' // Если мы хотим указать color: element.style.color = 'red' // или 'rgb(255,0,0)', или '#f00' // Если хотим указать font-family: element.style.fontFamily = 'Arial'      

Обратите внимание, что имена свойств в style . [ property Name ] записываются в camelCase, в отличие от CSS-свойств, которые записываются через дефис.

Таким образом font - family превращается в font Family , а, например, background - color — в background Color .

При сомнениях в том, как правильно называется то или иное свойство, воспользуйтесь списком соответствий:

CSS JavaScript
background background
background-attachment backgroundAttachment
background-color backgroundColor
background-image backgroundImage
background-position backgroundPosition
background-repeat backgroundRepeat
border border
border-bottom borderBottom
border-bottom-color borderBottomColor
border-bottom-style borderBottomStyle
border-bottom-width borderBottomWidth
border-color borderColor
border-left borderLeft
border-left-color borderLeftColor
border-left-style borderLeftStyle
border-left-width borderLeftWidth
border-right borderRight
border-right-color borderRightColor
border-right-style borderRightStyle
border-right-width borderRightWidth
border-style borderStyle
border-top borderTop
border-top-color borderTopColor
border-top-style borderTopStyle
border-top-width borderTopWidth
border-width borderWidth
clear clear
clip clip
color color
cursor cursor
display display
filter filter
float cssFloat
font font
font-family fontFamily
font-size fontSize
font-variant fontVariant
font-weight fontWeight
height height
left left
letter-spacing letterSpacing
line-height lineHeight
list-style listStyle
list-style-image listStyleImage
list-style-position listStylePosition
list-style-type listStyleType
margin margin
margin-bottom marginBottom
margin-left marginLeft
margin-right marginRight
margin-top marginTop
overflow overflow
padding padding
padding-bottom paddingBottom
padding-left paddingLeft
padding-right paddingRight
padding-top paddingTop
page-break-after pageBreakAfter
page-break-before pageBreakBefore
position position
stroke-dasharray strokeDasharray
stroke-dashoffset strokeDashoffset
stroke-width strokeWidth
text-align textAlign
text-decoration textDecoration
text-indent textIndent
text-transform textTransform
top top
vertical-align verticalAlign
visibility visibility
width width

На практике

Скопировать ссылку "На практике" Скопировано

Саша Беспоясов советует

Скопировать ссылку "Саша Беспоясов советует" Скопировано

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

Инлайновые стили имеют более высокую специфичность — их труднее переопределить, и это мешает нормальной работе со стилями элемента.

Пример. Мы пишем библиотеку, которая умеет красиво рисовать кнопки. Если мы установим цвет и размер кнопки с помощью инлайновых стилей, то пользователь библиотеки не сможет их легко поменять. Использовать такую библиотеку никто не захочет

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

Представьте, что вы хотите сделать анимацию движения точки на экране так, чтобы движение было случайным. В CSS (пока что) этого сделать нельзя, только скриптами. И вот здесь изменение инлайновых стилей как раз кстати.

Для изменения таких стилей используется свойство style .

Используйте style , чтобы изменить или получить инлайновые стили элемента.

🛠 Чтобы переписать стиль элемента полностью, можно использовать css Text или set Attribute .

 element.style.cssText = 'color: blue; border: 1px solid black'element.setAttribute('style', 'color:red; border: 1px solid blue;') element.style.cssText = 'color: blue; border: 1px solid black' element.setAttribute('style', 'color:red; border: 1px solid blue;')      

🛠 Чтобы обновить значение конкретного свойства, а остальные оставить нетронутыми, используйте style . [ property Name ] :

 element.style.color = 'red'element.style.fontFamily = 'Arial' element.style.color = 'red' element.style.fontFamily = 'Arial'      

🛠 Чтобы сбросить значение, присвойте ему null .

 // Если у элемента прописано style="background-color: red; color: black;",// то такая запись:element.style.backgroundColor = null // . оставит только style="color: black;". // Если у элемента прописано style="background-color: red; color: black;", // то такая запись: element.style.backgroundColor = null // . оставит только style="color: black;".      

🛠 Численным свойствам, таким как margin , padding , border - width и другим, следует указывать не только значение, но и единицу измерения:

 element.style.marginTop = '50px' element.style.marginTop = '50px'      

Источник

Javascript Set CSS Set CSS styles with javascript

2. Global styles

 var style = document.createElement('style'); style.innerHTML = ` #target < color: blueviolet; >`; document.head.appendChild(style); 

global styles

3. CSSOM insertRule

 var style = document.createElement('style'); document.head.appendChild(style); style.sheet.insertRule('#target '); 

insertRule

While it might look similar to the 2nd option, it's definitely different.
As you can see in Chrome devtools, tag is empty, but the style (darkseagreen color) is applied to the element. Also the color can't be changed via devtools because Chrome doesn't allow editing dynamic CSS styles. Actually such behavior was the motivation to write this post. A popular CSS-in-JS library Styled Components use this feature to inject styles in production mode because of performance. This feature might be undesirable in specific projects or environments and some folks complain about it in the project's issues.

4. Constructable Stylesheets (July 2019 update)

// Create our shared stylesheet: const sheet = new CSSStyleSheet(); sheet.replaceSync('#target '); // Apply the stylesheet to a document: document.adoptedStyleSheets = [sheet]; 

More details are here.
This option is only valid for Chrome, so use with caution. Do you know other options to add styles with javascript? What is your preferred option these days? Thanks for reading!

Источник

Читайте также:  Python ip camera stream
Оцените статью