JavaScript Style Summary : in this tutorial, you will learn how to use the style property to manipulate the inline style of the HTML elements.
Setting inline styles To set the inline style of an element, you use the style property of that element:
element .style
Code language: CSS ( css ) The style property returns the read-only CSSStyleDeclaration object that contains a list of CSS properties. For example, to set the color of an element to red , you use the following code:
element.style.color = 'red' ;
Code language: JavaScript ( javascript ) If the CSS property contains hyphens ( — ) for example -webkit-text-stroke you can use the array-like notation ( [] ) to access the property:
element.style.['-webkit-text-stock' ] = 'unset' ;
Code language: JavaScript ( javascript ) The following table shows the common CSS properties:
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 z-index zIndex
To completely override the existing inline style, you set the cssText property of the style object. For example:
element.style.cssText = 'color:red;background-color:yellow' ;
Code language: JavaScript ( javascript ) Or you can use the setAttribute() method:
element.setAttribute('style' ,'color:red;background-color:yellow' );
Code language: JavaScript ( javascript ) Once setting the inline style, you can modify one or more CSS properties:
element.style.color = 'blue' ;
Code language: JavaScript ( javascript ) If you do not want to completely overwrite the existing CSS properties, you can concatenate the new CSS property to the cssText as follows:
element.style.cssText += 'color:red;background-color:yellow' ;
Code language: JavaScript ( javascript ) In this case, the += operator appends the new style string to the existing one.
The following css() helper function is used to set multiple styles for an element from an object of key-value pairs:
function css (e, styles ) < for (const property in styles) e.style[property] = styles[property]; >
Code language: JavaScript ( javascript ) You can use this css() function to set multiple styles for an element with the id #content as follows:
let content = document .querySelector('#content' ); css(content, < background : 'yellow' , border : 'solid 1px red' >);
Code language: JavaScript ( javascript ) The following example uses the style object to set the CSS properties of a paragraph with the id content :
html >
html > head > meta charset ="utf-8" > title >JS Style Demo title> head> body > p id ="content" >JavaScript Setting Style Demo! p> script > let p = document .querySelector('#content' ); p.style.color = 'red' ; p.style.fontWeight = 'bold' ; script> body> html>Code language: HTML, XML ( xml ) First, select the paragraph element whose id is content by using the querySelector() method. Then, set the color and font-weight properties of the paragraph by setting the color and fontWeight properties of the style object. Getting inline styles The style property returns the inline styles of an element. It is not very useful in practice because the style property doesn’t return the rules that come from elsewhere e.g., styles from an external style sheet.
To get all styles applied to an element, you should use the window.getComputedStyle() method.
Summary Use the properties of element.style object to set the inline CSS properties for the HTML element. Источник
Стили CSS | JavaScript Как вставить, изменить или удалить CSS в атрибуте style style (все способы работы с атрибутами в JavaScript) --> есть ли атрибут this.hasAttribute('style'));">есть ли атрибут что содержит this.getAttribute('style'));">что содержит что содержит this.style.cssText);">что содержит количество свойств this.style.length);">количество свойств 1-ое свойство this.style[0]);">1-ое свойство 1-ое свойство this.style.item(0));">1-ое свойство значение свойства this.style.getPropertyValue('color'));">значение свойства значение свойства this.style.color);">значение свойства значение 1-ого свойства this.style.getPropertyValue(this.style[0]));">значение 1-ого свойства значение 1-ого свойства this.style.getPropertyValue(this.style.item(0)));">значение 1-ого свойства задать this.setAttribute('style', 'color: red; font-weight: bold;');">задать задать this.style.cssText = 'color: red; font-weight: bold;';">задать задать значение свойству this.style.setProperty('color', 'red'); this.style.setProperty('font-weight', 'bold');">задать значение свойству задать значение свойству this.style.color='red'; this.style.fontWeight='bold';">задать значение свойству поменять this.setAttribute('style', 'color: red; font-weight: bold;');">поменять поменять this.style.cssText = 'color: red; font-weight: bold;';">поменять поменять значение свойству this.style.setProperty('color', 'red');">поменять значение свойству поменять значение свойству this.style.color = 'red';">поменять значение свойству поменять значение 1-ого свойства this.style.setProperty(this.style[0], 'red');">поменять значение 1-ого свойства поменять значение 1-ого свойства this.style.setProperty(this.style.item(0), 'red');">поменять значение 1-ого свойства удалить this.removeAttribute('style');">удалить очистить this.style.cssText = '';">очистить убрать свойство this.style.removeProperty('color');">убрать свойство убрать свойство this.style.color = '';">убрать свойство убрать 1-ое свойство this.style.removeProperty(this.style[0]);">убрать 1-ое свойство убрать 1-ое свойство this.style.removeProperty(this.style.item(0));">убрать 1-ое свойство Как добавить, поменять или убрать CSS в теге или
button.dva < color: red; >@media (min-width: 30em) < button.dva < font-weight: bold; >> button.tri отключить document.getElementById('raz1').sheet.disabled = true;">отключить подключить document.getElementById('raz1').sheet.disabled = false;">подключить или document.getElementById('raz1').sheet.ownerNode.tagName);"><style> или <link> атрибут href document.getElementById('raz1').sheet.href);">атрибут href другие методы для работы с media на сайте arininav.ru --> атрибут media document.getElementById('raz1').sheet.media.mediaText);">атрибут media el.sheet или document.styleSheets[0]
не меняют HTML-содержимое тега, они меняют содержимое интерфейса CSSStyleSheet --> что содержит тег document.getElementById('raz1').innerHTML);">что содержит тег <style> CSSStyleSheet CSSStyleSheet количество правил document.getElementById('raz1').sheet.cssRules.length);">количество правил 1-ое правило document.getElementById('raz1').sheet.cssRules[0].cssText);">1-ое правило 2-е правило document.getElementById('raz1').sheet.cssRules[1].cssText);">2-е правило 1-ое правило 2-ого правила document.getElementById('raz1').sheet.cssRules[1].cssRules[0].cssText);">1-ое правило 2-ого правила селекторы 1-ого правила document.getElementById('raz1').sheet.cssRules[0].selectorText);">селекторы 1-ого правила тип селекторов 1-ого правила document.getElementById('raz1').sheet.cssRules[0].type);">тип селекторов 1-ого правила свойства и значения у селекторов 1-ого правила document.getElementById('raz1').sheet.cssRules[0].style.cssText);">свойства и значения у селекторов 1-ого правила количество свойств у селекторов 1-ого правила document.getElementById('raz1').sheet.cssRules[0].style.length);">количество свойств у селекторов 1-ого правила 1-ое свойство у селекторов 1-ого правила document.getElementById('raz1').sheet.cssRules[0].style[0]);">1-ое свойство у селекторов 1-ого правила значение свойства селекторов 1-ого правила document.getElementById('raz1').sheet.cssRules[0].style.getPropertyValue('color'));">значение свойства селекторов 1-ого правила значение свойства селекторов 1-ого правила document.getElementById('raz1').sheet.cssRules[0].style.color);">значение свойства селекторов 1-ого правила значение 1-ого свойства селекторов 1-ого правила s.getPropertyValue(s[0]));">значение 1-ого свойства селекторов 1-ого правила добавить правило на 4-ю позицию document.getElementById('raz1').sheet.insertRule('button.chetyre ', 3);">добавить правило на 4-ю позицию задать значение свойству в 3-м правиле document.getElementById('raz1').sheet.cssRules[2].style.setProperty('color', 'green');">задать значение свойству в 3-м правиле задать значение свойству в 3-м правиле document.getElementById('raz1').sheet.cssRules[2].style.color = 'green';">задать значение свойству в 3-м правиле поменять набор свойств или их значения в 3-ем правиле document.getElementById('raz1').sheet.cssRules[2].style.cssText = 'font-weight: bold; color: red;';">поменять набор свойств или их значения в 3-ем правиле поменять значение свойству в 3-ем правиле document.getElementById('raz1').sheet.cssRules[2].style.setProperty('font-weight', 'normal');">поменять значение свойству в 3-ем правиле поменять значение свойству в 3-ем правиле document.getElementById('raz1').sheet.cssRules[2].style.fontWeight = 'normal';">поменять значение свойству в 3-ем правиле поменять значение 1-ого свойства в 3-ем правиле var s = document.getElementById('raz1').sheet.cssRules[2].style; s.setProperty(s[0], 'normal');">поменять значение 1-ого свойства в 3-ем правиле удалить 4-ое правило document.getElementById('raz1').sheet.deleteRule(3);">удалить 4-ое правило убрать из 3-его правила свойства, оставив только селектор document.getElementById('raz1').sheet.cssRules[2].style.cssText = '';">убрать из 3-его правила свойства, оставив только селектор убрать свойство у селекторов из 4-ого правила document.getElementById('raz1').sheet.cssRules[3].style.removeProperty('color');">убрать свойство у селекторов из 4-ого правила убрать свойство у селекторов из 4-ого правила document.getElementById('raz1').sheet.cssRules[3].style.color = '';">убрать свойство у селекторов из 4-ого правила убрать 1-ое свойство у селекторов из 4-ого правила var s = document.getElementById('raz1').sheet.cssRules[3].style; s.removeProperty(s[0]);">убрать 1-ое свойство у селекторов из 4-ого правила
Как создать, установить и подключить CSS с помощью JavaScript document.styleSheets[0].insertRule('@import "http://сайт.ru/css.css ";', 0); var l = document.createElement('LINK'); l.rel = 'stylesheet'; l.href = 'http://сайт.ru/css.css '; l.media = 'all'; document.getElementsByTagName('head')[0].appendChild(l); Как получить стиль элемента: getComputedStyle(element[, pseudoElt]) С помощью getComputedStyle(element[, pseudoElt]) можно узнать окончательное значение свойства CSS (искл. обобщённые свойства, например, font , background , border ), приведённое из %, em и др. единиц измерения в px.
button.raz:before getComputedStyle(this, '').getPropertyValue('font-size'))"> getComputedStyle(this, '').fontSize);"> псевдоэлемента --> getComputedStyle(this, ':before').getPropertyValue('font-size'))"> getComputedStyle(this, ':before').fontSize);"> Как удалить "px" parseFloat(getComputedStyle(this, ':before').getPropertyValue('font-size')) )"> Как скопировать (получить дубликат) стиль элемента список свойств CSS и их значения у тега список свойств CSS и их значения у тега Как узнать все свойства JS, работающие с CSS свойствами список свойств JS у атрибута style
список свойств JS у атрибута style
Источник