css 樣式分為行內樣式和 外部樣式:
1、javascript 獲得行內樣式 :
可以使用 ele.style."屬性名稱"(如果遇到屬性名稱帶有"-", 需要使用駝峰方法,例如 background-color 改為 backgroundColor);
2、javascript 獲得外部樣式 ( getComputedStyle 可以獲得style 的值也可以獲得外部樣式表的css)
獲得外部樣式可以使用瀏覽器提供的 "window.getComputedStyle( ele,null )" 這里的ele 就是需要操作的對象,第二個參數是指定一個偽元素匹配,常規的元素用不上,直接使用null.
但是這個getComputedStyle 並不支持IE9 以下的瀏覽器,但是ie 他有自己支持的方法: ele.currentStyle;
所以為了達到兼容的問題,我們可以自己寫好一個通用的函數:
// html 部分
<style>
.getdivstyle{
background: red;
}
</style>
<div id="js-getdivstyle" class="getdivstyle" style="width:300px;height:300px;">測試</div>
// javascript 部分
<script>
// js調用部分
var getDivStyle = getId("js-getdivstyle");
getStyle( getDivStyle, "width");
getStyle( getDivStyle, "background-color"); // 這里的屬性選擇駝峰或者是默認加“-”的屬性都可以,但是不能直接使用縮寫 “background”
// 封裝好的獲取樣式函數
function getStyle(obj,attr){
if(window.getComputedStyle){
return window.getComputedStyle(obj,null)[attr];
}else{
return obj.currentStyle[attr];
}
}
// 封裝好的獲取元素id
function getId(idName){
return document.getElementById(idName);
}
</script>
題外話
ele.style.屬性名 和 ele.cssText 以及 getComputedStyle(obj,null) 有什么區別
1、ele.style.屬性名 這里獲得的style 可以獲得屬性值,也可以設置修改他, 例如: ele.style.left = 10 + "px";
2、ele.cssText 其實跟style差不多,只不過它是獲得多個css樣式。例如 : ele.style.cssText = "font-size:16px; height:250px" 也是生成在行內樣式中。
3、 getComputedStyle(obj,null) 只能獲取值不能修改,並且返回的css是一個 CSSStyleDeclaration 對象集合。詳細見: https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration