js笔记五十二之获取元素样式信息(1)
标签:
JavaScript
获取元素的某一个具体样式属性值
元素.style.属性名
需要我们把元素的样式都写在行内样式上才可以(写在样式表中是不管用的)
<style> #box{ height:240px; }</style><div id="box" style="width:100px">123</div><script>var box = document.getElementById("box");console.log(box.style.height); // -> ""console.log(box.style.width); // -> "100px"// 在真实项目中这种方式不常用, 因为真实项目中不能为了获取值吧所有样式都写在行内(无法实现css和html的分离)</script>
使用window.ComputedStyle这个办法获取所有经过浏览器计算过的样式
所有经过浏览器计算过的样式: 只要当前的元素标签可以在页面中呈现出来, 那么他的所有样式都是经过浏览器计算过的(渲染过的) -> 哪怕有些样式没有写,也可以获取到
window.getComputedStyle(当前要操作的元素对象,当前元素的伪类[一般不用伪类写null])
var box = document.getElementById("box");console.log(window.getComputedStyle); // -> function -> 方法console.log(window.getComputedStyle(box,null).height)
方法虽然好用,但是在IE6~8下不兼容: 因为window下没有
getComputedStyle
这个属性 -> 在IE6~8下执行这个方法会报错
在IE6~8下可以使用currentStyle
来获取所有经过浏览器就算过的样式
console.log(box.currentStyle.height);
处理兼容
getCss
: 获取当前元素所有经过浏览器计算过的样式中的[attr]对应的值curEle
: [object]要获取的样式属性的名称attr
: [string]要获取的样式属性的名称
// 1. 使用try,catch来处理兼容(只有在不得已的情况下才使用)// 前提: 必须保证try中的代码在不兼容浏览器中执行的时候报错,这样的话才可以用catch捕获到异常的信息,进行其他的处理;// 不管当前是什么浏览器,都需要先把try中的代码执行一遍,如果当前是IE7,window.getElementStyle本身是不兼容的,但是我也要先把他执行一遍,报错了,再把curEle.currentStyle执行一遍(消耗性能)function getCss(curEle,attr){ var val = null; try{ val = window.getComputedStyle(curEle, null)[attr]; }catch(e){ val = curEle.currentStyle[attr]; } return val; }console.log(getCss(box,"height"));
// 2.判断当前浏览器中是否存在这个属性或方法,存在就兼容,不存在就不兼容;function getCSS(curEle, attr){ var val = null; if("getComputedStyle" in window){ // -> 如果返回的是true,说明window下有getComputedStyle这个属性,代表兼容 val=window.getComputedStyle(curEle,null)[attr]; }else{ // 代表不兼容 val = curEle.currentStyle[attr]; } return val; }console.log(getCss(box,"height"));// 2.1 function getCSS(curEle, attr){ var val = null; if(window.getComputedStyle){ // 首先获取属性值,兼容返回的是一个函数,转换为布尔值是true; // 不兼容返回的是undefined,转换为布尔值是false; val=window.getComputedStyle(curEle,null)[attr]; }else{ val = curEle.currentStyle[attr]; } return val; }console.log(getCss(box,"height"));// 2.2function getCSS(curEle, attr){ var val = null; if(typeof window.getComputedStyle === "function"){ val=window.getComputedStyle(curEle,null)[attr]; }else{ val = curEle.currentStyle[attr]; } return val; }console.log(getCss(box,"height"));
// 3.通过检测浏览器版本来处理兼容 // window.navigator.userAgent // -> 获取浏览器信息 // 获取当前浏览器是IE6~8// /MSIE (6|7|8)/.test(navigator.userAgent)function getCSS(curEle, attr){ var val = null; if(/MSIE (6|7|8)/.test(navigator.userAgent)){ val = curEle.currentStyle[attr]; }else{ val=window.getComputedStyle(curEle,null)[attr]; } return val; }console.log(getCss(box,"height"));
作者:uplyw
链接:https://www.jianshu.com/p/8b316327d046
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦