平時給元素設置行內樣式,例如 <div id="div1" style="width:500px;"></div>,我們可以直接用 document.getElementById("div1").style.width 來讀取或設置。但一旦樣式寫在外鏈 link 或頁面內的非行內樣式中,這種方法就無能為力了。
這時需要區分浏覽器環境:標準浏覽器可以通過 window.getComputedStyle(obj, null)[property] 來獲取外鏈樣式,而舊版 IE 則要用 obj.currentStyle。
<!DOCTYPE html> <html> <head> <title>js獲取元素的外鏈樣式</title><base target="_blank"/> <style type="text/css"> p { width: 500px; line-height: 30px; } </style> <script src="https://jb51.net/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]; } return null; } $(document).ready(function(){ $("p").click(function(){ alert(getstyle(this,"width")); }); }); </script> </head> <body> <p style="width:750px;">如果您點擊我,彈出寬度。</p> <p>點擊我,彈出寬度。</p> <p>也要點擊我哦。</p> <div><a href="https://jb51.net">首頁</a> <a href="https://jb51.net/phtml/">特效庫</a> <a href="https://jb51.net/a/bjae/nb9lb3sd.htm">原文</a></div> </body> </html>
關鍵在於 getstyle 函數的兼容處理:優先判斷 currentStyle(IE),否則退回 getComputedStyle(標準浏覽器),這樣就能同時拿到行內與外鏈樣式。希望這份實現能給你帶來參考。