国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-20 21:14:27
字體:
來源:轉載
供稿:網友

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

 

js在獲取css屬性時如果標簽中無style則無法直接獲取css中的屬性,所以需要一個方法可以做到這點。
getStyle(obj,attr) 調用方法說明:obj為對像,attr為屬性名必須兼容js中的寫法(可以參考:JS可以控制樣式的名稱寫法)。

Js代碼

復制代碼 代碼如下:

function getStyle(obj,attr){
    var ie = !+"/v1";//簡單判斷ie6~8
 if(attr=="backgroundPosition"){//IE6~8不兼容backgroundPosition寫法,識別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];
 }
}

完整實例測試代碼:
Html代碼

復制代碼 代碼如下:

<!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";//簡單判斷ie6~8
 if(attr=="backgroundPosition"){//IE6~8不兼容backgroundPosition寫法,識別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>

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿城市| 开远市| 正蓝旗| 鹤壁市| 治多县| 商洛市| 辽阳市| 抚州市| 石林| 县级市| 茶陵县| 镇巴县| 左权县| 芷江| 理塘县| 晋江市| 曲沃县| 吉首市| 旬阳县| 开鲁县| 舒城县| 武夷山市| 江达县| 庆阳市| 南木林县| 涞水县| 大石桥市| 都昌县| 多伦县| 遵义市| 资溪县| 大理市| 保靖县| 化德县| 湘阴县| 临沧市| 墨竹工卡县| 广宁县| 宾阳县| 金乡县| 舒城县|