首页 > 语言 > JavaScript > 正文

JS之获取样式的简单实现方法(推荐)

2024-05-06 14:51:43
字体:
来源:转载
供稿:网友

基本代码:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>Document</title>  <style>    div{      color:yellow;    }  </style></head><body>  <div style="width:100px;height:100px;background-color:red">This is div</div></body></html>

1.通过使用element.style属性来获取

<script>  var div = document.getElementsByTagName("div")[0];  console.log(div.style.color); //""  console.log(div.style.backgroundColor); //red</script>

element.style属性只能获取行内样式,不能获取<style>标签中的样式,也不能获取外部样式

由于element.style是元素的属性,我们可以对属性重新赋值来改写元素的显示。 

<script>    var div = document.getElementsByTagName("div")[0];    div.style['background-color'] = "green";    console.log(div.style.backgroundColor); //green  </script>

2.通过getComputedStyle和currentStyle来获取样式

getComputedStyle的使用环境是chrome/safari/firefox IE 9,10,11

<script>  var div = document.getElementsByTagName("div")[0];  var styleObj = window.getComputedStyle(div,null);  console.log(styleObj.backgroundColor); //red  console.log(styleObj.color); //yellow</script>

currentStyle在IE里能得到完美支持,chrome不支持,ff不支持

<script>    var div = document.getElementsByTagName("div")[0];    var styleObj = div.currentStyle;    console.log(styleObj.backgroundColor); //red    console.log(styleObj.color); //yellow  </script>

3.ele.style和getComputedStyle或者currentStyle的区别

3.1 ele.style是读写的,而getComputedStyle和currentStyle是只读的

3.2 ele.style只能得到行内style属性里面设置的CSS样式,而getComputedStyle和currentStyle还能得到其他的默认值

3.3 ele.style得到的是style属性里的样式,不一定是最终样式,而其他两个得到的是元素的最终CSS样式

4.获取样式兼容性写法

<script>    //获取非行间样式(style标签里的样式或者link css文件里的样式),obj是元素,attr是样式名    function getStyle(obj,attr){       //针对IE       if(obj.currentStyle){         return obj.currentStyle[attr];               //由于函数传过来的attr是字符串,所以得用[]来取值       }else{         //针对非IE         return window.getComputedStyle(obj,false)[attr];       }    }    /*       获取或者设置css属性        */    function css(obj,attr,value){       if(arguments.length == 2){         return getStyle(obj,attr);       }else{            obj.style[attr] = value;       }    }  </script>

 5.window.getComputedStyle(ele[,pseudoElt]);

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选