js獲取元素的樣式值簡單介紹

admin發表於2017-03-23

本章節介紹一下如何利用javascript獲取指定元素的樣式屬性值,這在實際應用中的使用非常的頻繁。

先看一段程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
window.onload=function(){
  var odiv=document.getElementById("thediv");
  var oshow=document.getElementById("show");
  oshow.innerHTML=odiv.style.width;
}
</script>
</head>
<body>
<div id="show"></div>
<div id="thediv" style="width:100px;height:100px;background:red;"></div>
</body>
</html>

以上程式碼實現了我們的要求,可以獲取div元素的width屬性值,但是需要特別注意的是,使用odiv.style.width類似的方式只能夠獲取在標籤內部通過style方式定義的樣式,如果要獲取非標籤內定義的樣式則需要使用其他方式。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
#thediv{
  width:100px;
  height:100px;
  background:red;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var odiv=document.getElementById("thediv");
  var oshow=document.getElementById("show");
   
  function getStyle(node,property){ 
    if(node.style[property]){ 
      return node.style[property]; 
    } 
    else if(node.currentStyle){ 
      return node.currentStyle[property]; 
    } 
    else if(document.defaultView&&document.defaultView.getComputedStyle){ 
      var style=document.defaultView.getComputedStyle(node,null); 
      return style.getPropertyValue(property); 
    } 
    return null; 
  } 
  oshow.innerHTML=getStyle(odiv,"width");
}
</script>
</head>
<body>
<div id="show"></div>
<div id="thediv"></div>
</body>
</html>

以上程式碼實現了我們的要求,能夠獲取指定元素的樣式屬性,這個比較全面,算是通用型。

關於上面的程式碼這裡就不多介紹了,具體可以參閱getComputedStyle()和currentStyle屬性的用法一章節。

相關文章