標籤:style blog http color 使用 os
為了提高使用者體驗,我們經常會動態修改Dom節點的樣式,各種瀏覽器差異比較大,我們如何應對?不斷嘗試,不斷總結~!
1. style、getComputedStyle、currentStyle
內嵌樣式:
<!--body -->
<div style="width: 30px;background-color: #ff6a00;">我就是傻裡傻氣的,完全素顏!</div>
1 //內聯樣式優先順序最高,通過style擷取的樣式是最準確的2 var elm = document.getElementById(‘J-demo‘);3 4 //通常這樣擷取5 elm.style.width6 elm.style.backgroundColor
內聯樣式、外部樣式:
<!--css--><link ref="stylesheet" href="demo.css"><style> .demo { width: 30px; background-color: #ff6a00; }</style><!--body --><div id="J-demo" class="demo">你想那麼容易看我素顏?沒那麼容易...</div>
1 var elm = document.getElementById(‘J-demo‘), 2 elmStyle; 3 4 elm.style.xxx //只能擷取定義的內聯樣式 5 6 //如果標籤沒有定義相關的內聯樣式,應該這麼辦: 7 elmStyle = elm.currentStyle ? elm.currentStyle.getAttribute(‘background-color‘) : window.getComputedStyle(elm, null).getPropertyValue(‘background-color‘); 8 9 getPropertyValue(name) //name不要使用駝峰命名的名稱10 getAttribute(name) //如果考慮該死的IE6, name 必須是駝峰命名的名稱11 12 //為什麼不用下標[name]來擷取屬性值呢?13 //瀏覽器對樣式屬性解釋名稱不一樣,比如float,有的叫cssFloat,有的叫styleFloat
2. screen屬性
//顯示器可用寬度、高度,不包含工作列availWidth、availHeight//顯示器螢幕的寬度、高度width、height
3. 元素視圖方法、屬性
1 //讓元素滾動到可視地區 2 scrollIntoView() 3 4 //內容地區的左上方相對於整個元素左上方的位置(包括邊框) 5 clientLeft 6 clientTop 7 8 //內容地區的高度和寬度,包括padding,不包括邊框和捲軸 9 clientWidth10 clientHeight11 12 //相對於最近的祖先定位元素的位移值13 offsetLeft14 offsetTop15 16 //第一個祖定位元素(用來計算offsetLeft和offsetTop的元素)17 offsetParent18 19 //ffsetParent元素只可能是下面這幾種情況:20 //1. <body>21 //2. position不是static的元素22 //3. <table>, <th> 或<td>,但必須要position: static23 24 //整個元素的尺寸(包括邊框)25 offsetWidth26 offsetHeight27 28 //元素滾動的像素大小,可讀可寫29 scrollLeft30 scrollTop31 32 //整個內容地區的寬高,包括隱藏部分33 scrollWidth34 scrollHeight35 //相容問題:當外層元素沒有設定overflow,但內容超過外層元素寬高時,瀏覽器擷取的值將不準確36 //解決方案:對外層元素設定overflow屬性
4. 滑鼠位置
1 //滑鼠相對於window的位移2 event.clientX3 event.clientY4 5 //滑鼠相對於顯示器螢幕的位移座標6 event.screenX7 event.screenY
.Thingking
學會這些通用的樣式處理方法,操作Dom樣式,製作出漂亮的頁面style,將會更加得心應手。
Reference: http://www.quirksmode.org/dom/w3c_cssom.html