兼容性如下图所示(摘自 mdn)
由于getcomputedstyle方法在ie浏览器中只兼容ie9及其以上,而ie8和它之前的浏览器则需要使用currentstyle方法来获取样式,所以我们就可以自定义一个getstyle方法来解决兼容性的问题
自定义getstyle()代码
function getstyle (obj, name) { if (obj.currentstyle) { return obj.currentstyle[name]; } else { return getcomputedstyle(obj)[name]; } }
完整html代码
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>getstyle</title> <style> div{ width: 200px; height: 200px; background-color: brown; } </style> <script> function getstyle (obj, name) { if (obj.currentstyle) { return obj.currentstyle[name]; } else { return getcomputedstyle(obj)[name]; } } window.onload = function () { // let box = document.queryselector("div"); var box = document.getelementsbytagname("div")[0]; var btn = document.getelementsbytagname("button")[0]; box.style.width = "250px"; box.style.height = "250px"; box.style.backgroundcolor = "skyblue"; btn.onclick = function () { alert(getstyle(box, "backgroundcolor")); }; }; </script> </head> <body> <div></div> <button>fun</button> </body> </html>
ie8
2.ie11
3.chrome
4.firefox
如对本文有疑问, 点击进行留言回复!!
【JavaScript笔记(一)】万丈高楼平地起 - 基本概念篇
轻松解决 org.apache.taglibs.standard.tlv.JstlCoreTLV 困惑
vert实践五——Json?Protocol Buffer?FlatBuffers?
[基于tensorflow的人脸检测] 基于神经网络的人脸检测8——验证训练好的神经网络
网友评论