有些效果必須靠 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。
邊框與清除
| CSS | JavaScript |
|---|---|
| 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 |
| float | cssFloat(IE 用 styleFloat) |
邊界與內距
| CSS | JavaScript |
|---|---|
| margin | margin |
| margin-bottom | marginBottom |
| margin-left | marginLeft |
| margin-right | marginRight |
| margin-top | marginTop |
| padding | padding |
| padding-bottom | paddingBottom |
| padding-left | paddingLeft |
| padding-right | paddingRight |
| padding-top | paddingTop |
背景與色彩
| CSS | JavaScript |
|---|---|
| background | background |
| background-attachment | backgroundAttachment |
| background-color | backgroundColor |
| background-image | backgroundImage |
| background-position | backgroundPosition |
| background-repeat | backgroundRepeat |
| color | color |
版面與列表
| CSS | JavaScript |
|---|---|
| display | display(隱藏時設為 none) |
| list-style-type | listStyleType |
| list-style-image | listStyleImage |
| list-style-position | listStylePosition |
| list-style | listStyle |
| white-space | whiteSpace |
字型
| CSS | JavaScript |
|---|---|
| font | font |
| font-family | fontFamily |
| font-size | fontSize |
| font-style | fontStyle |
| font-variant | fontVariant |
| font-weight | fontWeight |
文字
| CSS | JavaScript |
|---|---|
| letter-spacing | letterSpacing |
| line-break | lineBreak |
| line-height | lineHeight |
| text-align | textAlign |
| text-decoration | textDecoration |
| text-indent | textIndent |
| text-justify | textJustify |
| text-transform | textTransform |
| vertical-align | verticalAlign |
第一,float 是 JavaScript 保留字,所以標準寫法是 style.cssFloat,舊版 IE 則用 style.styleFloat。這是對照表裡唯一的例外,值得單獨記住。
第二,動態改樣式時數值記得帶單位,例如 el.style.width = "100px"。若要讀取由外部 CSS 設定的值(而非行內樣式),el.style.xxx 會是空的,得改用 getComputedStyle(el).xxx。