获取DOM元素样式
1、obj.currentStyle.styleName 只兼容IE
2、getComputedStyle(obj, false).styleName 不兼容IE8
于是有了兼容性写法:
function getStyle(obj, sName){ return (obj.currentStyle || getComputedStyle(obj, false))[sName]; }
demo:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DEMO - Lik</title> <style> div{ width:100px; height:200px; background:blue; } </style> </head> <body> <div></div> <script> function getStyle(obj, sName){ return (obj.currentStyle || getComputedStyle(obj, false))[sName]; } var oDiv = document.getElementsByTagName('div')[0]; console.log(getStyle(oDiv, 'width')); // 100px console.log(getStyle(oDiv, 'height')); // 200px console.log(getStyle(oDiv, 'background')); // rgb(0, 0, 255) none repeat scroll 0% 0% / auto padding-box border-box </script> </body> </html>
author:Lik
Endeavoring to powerless, struggling to move yourself.
Endeavoring to powerless, struggling to move yourself.