DIV CSS 佈局教程網

用 JavaScript 動態修改 CSS:style 屬性對照表
編輯:關於JavaScript     

有些效果必須靠 JavaScript 動態改樣式才能做到。例如滑鼠移入圖片時加上邊框:

<script type="text/javascript">
function imageOver(e) {
  e.style.border = "1px solid red";
}
function imageOut(e) {
  e.style.borderWidth = 0;
}
</script>
<img src="phplamp.gif" onmouseover="imageOver(this)" onmouseout="imageOut(this)" />

問題來了:CSS 裡寫 border-bottom-color,在 JavaScript 裡該寫成什麼?

規則很簡單:凡是帶連字號的 CSS 屬性,轉成駝峰式(camelCase)——去掉連字號,把後面的字母大寫。所以 background-color 變成 backgroundColor,font-size 變成 fontSize。

style 屬性對照表

邊框與清除

CSSJavaScript
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
floatcssFloat(IE 用 styleFloat)

邊界與內距

CSSJavaScript
marginmargin
margin-bottommarginBottom
margin-leftmarginLeft
margin-rightmarginRight
margin-topmarginTop
paddingpadding
padding-bottompaddingBottom
padding-leftpaddingLeft
padding-rightpaddingRight
padding-toppaddingTop

背景與色彩

CSSJavaScript
backgroundbackground
background-attachmentbackgroundAttachment
background-colorbackgroundColor
background-imagebackgroundImage
background-positionbackgroundPosition
background-repeatbackgroundRepeat
colorcolor

版面與列表

CSSJavaScript
displaydisplay(隱藏時設為 none)
list-style-typelistStyleType
list-style-imagelistStyleImage
list-style-positionlistStylePosition
list-stylelistStyle
white-spacewhiteSpace

字型

CSSJavaScript
fontfont
font-familyfontFamily
font-sizefontSize
font-stylefontStyle
font-variantfontVariant
font-weightfontWeight

文字

CSSJavaScript
letter-spacingletterSpacing
line-breaklineBreak
line-heightlineHeight
text-aligntextAlign
text-decorationtextDecoration
text-indenttextIndent
text-justifytextJustify
text-transformtextTransform
vertical-alignverticalAlign

兩個實務提醒

第一,float 是 JavaScript 保留字,所以標準寫法是 style.cssFloat,舊版 IE 則用 style.styleFloat。這是對照表裡唯一的例外,值得單獨記住。

第二,動態改樣式時數值記得帶單位,例如 el.style.width = "100px"。若要讀取由外部 CSS 設定的值(而非行內樣式),el.style.xxx 會是空的,得改用 getComputedStyle(el).xxx。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved