元素樣式有幾種形式掸茅,其中:
外部樣式:HTML 中通過 <link> 標(biāo)簽引入的 CSS 文件樣式。
<link rel="stylesheet" href="main.css">
-
內(nèi)部樣式:寫在 HTML 文檔中柠逞,<style> 標(biāo)簽中設(shè)置的 CSS 昧狮。
<style> .box { height: 100px; width: 100px; } </style>
行內(nèi)(內(nèi)聯(lián))樣式:寫在元素標(biāo)簽內(nèi)的樣式。
<div class="box" style="height: 100px;width: 100px"> 內(nèi)聯(lián)樣式 </div>
使用 JS 獲取各種樣式的方法(從內(nèi)到外順序):
-
獲取行內(nèi)(內(nèi)聯(lián))樣式
使用 Obj.style.attributeName
先獲取元素板壮,隨后獲取 style 屬性 中的樣式逗鸣,可以返回樣式的值。
var box = document.getElementById("box");
alert(box.style.height) // 獲取 box 的行內(nèi)樣式 height 的值如 100px
使用 Obj.getAttribute('style')
該方法返回所有行內(nèi)樣式绰精,即行內(nèi)屬性 style 的值
var box = document.getElementById("box");
alert( box.getAttribute('style') );
// 獲得字符串撒璧,如 "height: 100px; width: 100px;"
-
獲取非內(nèi)聯(lián)的樣式
- 在 ie 瀏覽器中 ——
obj.currentStyle['height']
- 非 ie 瀏覽器中 ——
getComputedStyle(obj).height
這兩個方法,
原理是返回該元素最終應(yīng)用上的樣式屬性笨使,即該元素被設(shè)置的所有屬性卿樱。
其中,currentStyle[] 和 obj.style 比較接近硫椰,都可以支持讀寫繁调。
而 getComputedStyle(obj) 只能讀萨蚕,不是能進(jìn)行值的改寫。 - 在 ie 瀏覽器中 ——
jQuery 中獲取 CSS 樣式蹄胰,很簡單岳遥,$().css()
大神來補充——獲取元素CSS值之getComputedStyle方法熟悉
Wait me back