如何避免获取复合值时浏览器之间差异
- // 写 CSS 的时候第一步初始化默认样式, 避免浏览器之间的差异 ->
- // 不仅如此, 而且写默认样式对于 js 以后获取到的结果统一也是有帮助的
- function getCSS(curEle, attr){
- var val = null;
- if("getComputedStyle" in window){
- val=window.getComputedStyle(curEle,null)[attr];
- }else{
- val = curEle.currentStyle[attr];
- }
- return val;
- }
- // -> 标准浏览器和 IE 浏览器获取的结果还是不一样的 -> 对于部分样式属性, 不同的浏览器获取的结果不一样,
- // 主要是由于 getComputedStyle 和 currentStyle 在某些方面不一样
- console.log(getCss(box,"border")); // undefined
- // 把复合值拆开来写能避免这一问题
- console.log(getCss(box,"borderTopWidth")); // 10px
第一次升级: 把获取到的样式值 "单位去掉"
- function getCSS(curEle, attr){
- var val = null;
- if("getComputedStyle" in window){
- val=window.getComputedStyle(curEle,null)[attr];
- }else{
- val = curEle.currentStyle[attr];
- }
- return parseFloat(val);
- // -> 去单位这样写不行, 对于某些样式属性的值是不能去单位的;
- // -> 例如 float, position, margin, padding, border 的复合值等等...
- }
- console.log(getCss(box,"width"));
- // 利用正则
- function getCSS(curEle, attr){
- var val = null, reg = null;
- if("getComputedStyle" in window){
- val=window.getComputedStyle(curEle,null)[attr];
- }else{
- val = curEle.currentStyle[attr];
- }
- reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?$/i;
- return reg.test(val) ? parseFlort(val) : val;
- }
- console.log(getCss(box,"width"));
第二次升级: 有些样式属性在不同的浏览器中是不兼容的, 例如: opacity
- // opacity:0.1; 透明度, 在 IE6~8 中不兼容
- // filter:alpha(opacity=10); 不兼容 使用滤镜来处理;
- function getCSS(curEle, attr){
- var val = null, reg = null;
- if("getComputedStyle" in window){
- val=window.getComputedStyle(curEle,null)[attr];
- }else{
- // IE6~8;
- // 如果传递进来的结果是 opacity, 说明要获取的是透明度, 但是在 IE6~8 下获取透明度需要使用 filter
- if(attr === "opacity"){
- val = curEle.currentStyle["filter"]; // -> "alpha(opacity=10)"
- // 把获取到的结果进行剖析, 获取里面的数字, 让数字除以 100 才和标准的浏览器保持一致
- reg = /^alpha\(opacity=(\d+(?:\.\d+)?)\)$/i;
- val = reg.test(val)?reg.exec(val)[1]/100:1;
- }else{
- val = curEle.currentStyle[attr];
- }
- }
- reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?$/i;
- return reg.test(val) ? parseFlort(val) : val;
- }
- console.log(getCss(box,"opacity"));
补充: css 伪类元素获取
- <style type="text/css">
- #box{
- width: 300px;
- padding: 30px;
- border: 1px dashed #ddd;
- margin: 50px auto;
- }
- #box:before{
- display: block;
- content: "标题";
- background: lightgreen;
- line-height: 1.5;
- text-align: center;
- }
- #box:after{
- display: block;
- content: "结尾";
- background: lightgreen;
- line-height: 1.5;
- text-align: center;
- }
- </style>
- <div id="box"> 这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字 </div>
- <script>
- var box = document.getElementById("box")
- console.log(window.getComputedStyle(box, "before").content)
- console.log(window.getComputedStyle(box, "after").lineHeight)
- </script>
来源: http://www.jianshu.com/p/e6f90568336d