Adding style from javascript

.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'      

Источник

Setting CSS Styles with JavaScript

Setting CSS Styles with JavaScript

Why is there a need to change CSS with Javascript? Let’s discuss a few cases where changing CSS styles in Javascript makes sense.

  1. To load stylesheets dynamically.
  2. After an initial page render, sometimes, there will be a need to change a particular style for the element in a page dynamically. In cases like this, writing CSS in Javascript helps.
  3. If on any webpage some progress is happening and we want to change the look and feel after progress is finished. Here as well, changing styles in Javascript helps.
  4. Many developers are much more confident in writing Javascript than CSS, for those, it is hard to write and maintain CSS. So they like to write CSS in Javascript. There are libraries that allow to style components with CSS in Javascript like style components.

Above are a few which I can think of, but I am sure there are many.

How to change CSS with Javascript?

There are different ways of setting CSS with Javascript for different scenarios. Below is the list :

  • Inline style
  • Adding or removing class names from the element
  • Global styles
  • Adding or replacing stylesheets
  • Inserting CSS rules

Let’s discuss each one in detail.

Inline style is the way to add styles directly to elements. The highlighted part of the devtool image below shows how red color and font size got added to the title. Inline styles can also be written directly on an element, but here we will look at how we can achieve the inline style in Javascript.

Adding red color and font size to the title

Adding red color and font size to the title

We have an H1 element with the default styles and with an Id attribute, which has a value ‘title’. Below is the image which shows HTML view, browser view and devtool view of the H1 element.

HTML view, browser view, and devtool view of the H1 element.

HTML view, browser view, and devtool view of the H1 element.

Now, will change the font size and color of the H1 element to 50px and red respectively. In CSS we will apply styles on elements ID.

Источник

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!

Источник

Читайте также:  Check class with javascript
Оцените статью