javascript通用獲取元素樣式屬性值代碼實例
本章節分享一段代碼實例,它實現了具有通用效果的獲取元素指定樣式屬性值的功能。無論是使用ele.style.attr方式定義的屬性還是樣式表定義的屬性,都可以獲取。
代碼實例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="/" />
<title>實例</title>
<style type="text/css">
#antzone{
width:200px;
height:100px;
background-color:#ccc;
text-align:center;
line-height:100px;
}
</style>
<script type="text/javascript">
function getStyle(elem, name) {
if (elem.style[name]) {
return elem.style[name];
}
else if (elem.currentStyle) {
return elem.currentStyle[name];
}
else if(document.defaultView && document.defaultView.getComputedStyle){
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
var s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
}
else {
return null;
}
}
window.onload=function(){
var odiv=document.getElementById("antzone");
odiv.innerHTML=getStyle(odiv,"backgroundColor");
}
</script>
</head>
<body>
<div id="antzone"></div>
</body>
</html>
上面的代碼實現了我們的要求,下面介紹一下它的實現過程。
一.代碼注釋:
(1).function getStyle(elem, name) {},此方法實現了獲取功能,第一個參數元素對象,第二個參數是屬性的名稱,符合屬性支持類似"backgroundColor"和"background-color"兩種形式。
(2).if (elem.style[name]) {
return elem.style[name];
},如果是屬性是使用style定義的,那么就使用此種方式獲取。
(3).else if (elem.currentStyle) {
return elem.currentStyle[name];
},此方式是針對IE8和IE8以下瀏覽器。
(4). else if(document.defaultView && document.defaultView.getComputedStyle),針對標準瀏覽器。
(5).name = name.replace(/([A-Z])/g, "-$1")此代碼就是為了將backgroundColor形式轉換為background-color。
(6).name = name.toLowerCase(),轉換為小寫形式。
(7).var s = document.defaultView.getComputedStyle(elem, ""),獲取元素的css樣式對象。
(8).return s && s.getPropertyValue(name),獲取指定名稱的屬性值。
(1).currentStyle可以參閱getComputedStyle()和currentStyle屬性的一章節。
(2).replace()方法可以參閱正則表達式replace()一章節。
相關推薦
-
js動態設置元素透明度代碼實例
本章節分享一段代碼實例,它實現了動態設置元素透明度效果。當然這個動態設置不是指的以動畫方式設置透明度。以動畫方式設置透明度可以參閱jvscrit實現的以漸變方式設置透明度一章節。代碼實例如下:
-
javascript命名空間使用簡單代碼實例
代碼實例如下:vr GLOBL = {};GLOBL.nmsc = function(str){vr rr = str.slit(.),o = GLOBL;for(k=(rr
-
javascript如何判斷指定類型元素是否具有指定屬性
本章節分享一段代碼實例,它實現了判斷一個指定類型的元素是否具有指定的屬性。代碼實例如下:function lmntSuortsttribut(lmnt, ttribut) {
-
javascript為什么字符串直接量可以使用屬性和方法
在分析標題中的問題之前先來看一段代碼實例:vr str=實例3;consol.log(str.lngth);如果不深究,那么上面的代碼實在是太普通不過了,但是細致看來,可能有不少朋友有
-
js將字符串轉換為編碼序列代碼實例
本章節分享一段代碼實例,它實現了將字符串轉換為編碼序列的功能。代碼如下:vr str=實例3;vr rr=str.slit();vr codrr=rr.m(funct















