一般給元素設置行內樣式,如<div id="div1"></div>。如要獲取它的樣式,即可document.getElementById("div1").style.width來獲取或設置。但是如果樣式是在外鏈link中的或者是頁面的非行內樣式,就獲取不到了。
在標準瀏覽器中可以通過window.getComputedStyll(obj,null)[property]來獲取外鏈樣式,但是在ie瀏覽器中則是通過obj.currentStyle來獲取。
完整html代碼:
<!DOCTYPE html><html><head> <title>js獲取元素的外鏈樣式</title><base target="_blank"/> <style type="text/css"> p { width: 500px; line-height: 30px; } </style> <script src="http://VeVB.COm/jquery/jquery-1.11.2.min.js"> </script> <script>function getstyle(obj,property){if(obj.currentStyle){return obj.currentStyle[property];}else if(window.getComputedStyle){return document.defaultView.getComputedStyle(obj,null)[property];//或者也可以通過window.getComputedStyle來獲取樣式}return null;}$(document).ready(function(){$("p").click(function(){alert(getstyle(this,"width"));});}); </script></head><body> <p>如果您點擊我,彈出寬度。 </p> <p>點擊我,彈出寬度。 </p> <p>也要點擊我哦。 </p> <div><a href="http://VeVB.COm">首頁</a> <a href="http://VeVB.COm/phtml/">特效庫</a> <a href="http://VeVB.COm/a/bjae/nb9lb3sd.htm">原文</a></div></body></html>以上這篇js獲取元素的外鏈樣式的簡單實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。