Setting inline styles 设置内联样式
要设置元素的内联样式,可以使用style
该元素的属性:
element.style
该属性返回包含 CSS 属性列表的style
只读对象。CSS样式申请如下
例如,要将元素的颜色设置为red
,请使用以下代码:
element.style.color = 'red';
例如,如果CSS属性包含连字符( – )“-webkit-text-stroke”.您可以使用类似数组的符号([])访问属性:
element.style.['-webkit-text-stock'] = 'unset';
下表显示了常见的CSS属性:
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 |
要完全覆盖现有的内联样式,您可以设置样式对象的csstext属性。例如:
element.style.cssText = 'color:red;background-color:yellow';
或者,您可以使用setAttribute()方法:
element.setAttribute('style','color:red;background-color:yellow');
设置内联样式后,您可以修改一个或多个CSS属性:
element.style.color = 'blue';
如果您不想完全覆盖现有的CSS属性,则可以将新的CSS属性与CSStext相连,如下所示:
element.style.cssText += 'color:red;background-color:yellow';