获取元素的某一个具体样式属性值
元素. style. 属性名
需要我们把元素的样式都写在行内样式上才可以(写在样式表中是不管用的)
使用 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.2
- function 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"));
来源: http://www.jianshu.com/p/8b316327d046