JavaScript Style

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属性:

CSSJavaScript
backgroundbackground
background-attachmentbackgroundAttachment
background-colorbackgroundColor
background-imagebackgroundImage
background-positionbackgroundPosition
background-repeatbackgroundRepeat
borderborder
border-bottomborderBottom
border-bottom-colorborderBottomColor
border-bottom-styleborderBottomStyle
border-bottom-widthborderBottomWidth
border-colorborderColor
border-leftborderLeft
border-left-colorborderLeftColor
border-left-styleborderLeftStyle
border-left-widthborderLeftWidth
border-rightborderRight
border-right-colorborderRightColor
border-right-styleborderRightStyle
border-right-widthborderRightWidth
border-styleborderStyle
border-topborderTop
border-top-colorborderTopColor
border-top-styleborderTopStyle
border-top-widthborderTopWidth
border-widthborderWidth
clearclear
clipclip
colorcolor
cursorcursor
displaydisplay
filterfilter
floatcssFloat
fontfont
font-familyfontFamily
font-sizefontSize
font-variantfontVariant
font-weightfontWeight
heightheight
leftleft
letter-spacingletterSpacing
line-heightlineHeight
list-stylelistStyle
list-style-imagelistStyleImage
list-style-positionlistStylePosition
list-style-typelistStyleType
marginmargin
margin-bottommarginBottom
margin-leftmarginLeft
margin-rightmarginRight
margin-topmarginTop
overflowoverflow
paddingpadding
padding-bottompaddingBottom
padding-leftpaddingLeft
padding-rightpaddingRight
padding-toppaddingTop
page-break-afterpageBreakAfter
page-break-beforepageBreakBefore
positionposition
stroke-dasharraystrokeDasharray
stroke-dashoffsetstrokeDashoffset
stroke-widthstrokeWidth
text-aligntextAlign
text-decorationtextDecoration
text-indenttextIndent
text-transformtextTransform
toptop
vertical-alignverticalAlign
visibilityvisibility
widthwidth
z-indexzIndex

要完全覆盖现有的内联样式,您可以设置样式对象的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';

Leave a comment

您的电子邮箱地址不会被公开。 必填项已用 * 标注