getcomputedstyle()获取border像素差异问题
getComputedStyle()方法返回的是一个CSS样式声明对象--CSSStyleDeclaration对象(与style属性的类型相同),包含当前元素所有最终使用的CSS属性值;
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 #myDiv { 8 background-color: #FFF; 9 width: 200px; 10 height: 200px; 11 } 12 </style> 13 </head> 14 <body> 15 <div id="myDiv" style="background-color: red; border: 1px solid #333;"></div> 16 </body> 17 <script> 18 var myDiv = document.getElementById('myDiv'); 19 var computedStyle = document.defaultView.getComputedStyle(myDiv, null); 20 console.log(computedStyle.backgroundColor);//rgb(255, 0, 0) 21 console.log(computedStyle.width);//200px 22 console.log(computedStyle.height);//200px 23 console.log(parseFloat(computedStyle.border));//1 24 console.log(computedStyle.border);//1px solid rgb(51, 51, 51)(chrome下) 25 //NaN(Firefox下) 26 //1px solid rgb(51, 51, 51)(Opera下) 27 </script> 28 </html>
IE不支持getComputedStyle()方法,取而代之的是
IE浏览器的一个属性currentStyle;
1 var myDiv = document.getElementById('myDiv'); 2 var computedStyle = myDiv.currentStyle; 3 console.log(computedStyle.backgroundColor); 4 console.log(computedStyle.width); 5 console.log(computedStyle.height); 6 console.log(computedStyle.border);//undefined
造成border差异原因:
border: 1px solid #333;是一个复合属性,浏览器在解析时把border解释为:borderleftwidth: 200px; borderleftcolor: #333; borderleftstyle: solid; ...一个div有四条边,每条边的样式(如宽度,颜色等)都可能不同,所以在不同的浏览器下输出结果会不一致;
延伸:与style.css区别
getComputedStyle()获取完整样式,而style.css仅能获得内联样式中的部分属性,无法获得层叠或继承来的外部属性;
使用注意点:
1、仅能设置内联样式中的css属性, css属性名(class-name)都要去横线变驼峰命名(className);
2、无论是获取/设置的css属性值必须都是字符串;获取时,要去单位,再计算;修改时,要补单位,再赋值;
声明:本博客的文章除特殊说明外均为原创,转载请注明出处;