最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

js獲取某元素的class里面的css屬性值代碼

 更新時(shí)間:2014年01月16日 15:14:38   作者:  
這篇文章主要介紹了js獲取某元素的class里面的css屬性值代碼,有需要的朋友可以參考一下

用js如何獲取div中css的 margin、padding、height、border等。你可能說(shuō)可以直接用document.getElementById("id").style.margin獲取。但是你說(shuō)的只能獲取直接在標(biāo)簽中寫的style的屬性,無(wú)法獲取標(biāo)簽style外的屬性(如css文件中的屬性)。而下面方法則兩者值都可以獲取。
實(shí)例效果圖如下:

 

js在獲取css屬性時(shí)如果標(biāo)簽中無(wú)style則無(wú)法直接獲取css中的屬性,所以需要一個(gè)方法可以做到這點(diǎn)。
getStyle(obj,attr) 調(diào)用方法說(shuō)明:obj為對(duì)像,attr為屬性名必須兼容js中的寫法(可以參考:JS可以控制樣式的名稱寫法)。

Js代碼

復(fù)制代碼 代碼如下:

function getStyle(obj,attr){
    var ie = !+"\v1";//簡(jiǎn)單判斷ie6~8
 if(attr=="backgroundPosition"){//IE6~8不兼容backgroundPosition寫法,識(shí)別backgroundPositionX/Y
  if(ie){       
   return obj.currentStyle.backgroundPositionX +" "+obj.currentStyle.backgroundPositionY;
     }
 }
 if(obj.currentStyle){
  return obj.currentStyle[attr];
 }
 else{
  return document.defaultView.getComputedStyle(obj,null)[attr];
 }
}

完整實(shí)例測(cè)試代碼:
Html代碼

復(fù)制代碼 代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>js獲取某元素的class里面的css屬性值</title>
<style>
#box1{margin:5px;padding:5px;height:100px;width:200px;}
a{border:1px solid #ccc;border-radius:3px;padding:3px 5px;margin:5px 0;display:inline-block;background:#eee;color:#f60;text-decoration:none;font-size:12px;}
a:hover{color:#ff0000;background:#fff;}
</style>
</head>

<body>
<div id="box1">box1的css.#box1{margin:5px;padding:5px;height:100px;width:200px;}</div>
<a href="javascript:;" onclick="getcss('marginTop')">獲取box1的margin-top</a><br />
<a href="javascript:;" onclick="getcss('paddingTop')">獲取box1的padding-top</a><br />
<a href="javascript:;" onclick="getcss('height')">獲取box1的height</a><br />

<script>
//獲取class里面的屬性值
var divs=document.getElementById("box1");
function getStyle(obj,attr){
    var ie = !+"\v1";//簡(jiǎn)單判斷ie6~8
 if(attr=="backgroundPosition"){//IE6~8不兼容backgroundPosition寫法,識(shí)別backgroundPositionX/Y
  if(ie){       
   return obj.currentStyle.backgroundPositionX +" "+obj.currentStyle.backgroundPositionY;
     }
 }
 if(obj.currentStyle){
  return obj.currentStyle[attr];
 }
 else{
  return document.defaultView.getComputedStyle(obj,null)[attr];
 }
}
function getcss(typ){
 alert(getStyle(divs,typ));
}
</script>
</body>
</html>

相關(guān)文章

最新評(píng)論

大渡口区| 邓州市| 泽州县| 蒲城县| 汕头市| 呈贡县| 武穴市| 永定县| 滕州市| 赣州市| 庆云县| 本溪市| 木里| 肃南| 乐业县| 招远市| 五常市| 体育| 城市| 阿勒泰市| 伊宁县| 沐川县| 宿州市| 长葛市| 临沧市| 涞水县| 随州市| 南丹县| 宜兰县| 灌南县| 岳池县| 龙陵县| 屏山县| 吴川市| 九龙县| 且末县| 青铜峡市| 车致| 桂东县| 南靖县| 汉中市|