可以通过JavaScript访问css的属性,并修改css属性

一. 获取和修改行间样式表

有2中方式访访问到行间样式表

  1. element.style.css属性名

  2. element.style["属性名"]

<body>
<div id="box1"></div>
<script type="text/javascript">
var box1 = document.getElementById("box1");
box1.style.width = "100px";    //设置css属性. 设置所有属性都要使用引号括起来。
box1.style["height"] = "100px";
.backgroundColor = "blue";
alert(box1.style["width"]);
</script>
</body>

二. 获取内部样式表和外部样式表

  1. 对ie浏览器:对象.currentSytle["属性名"]

  2. 其他浏览器:window.getComputedStyle(对象,null)["属性名"]

注意:

  • 内部样式表中的属性和外部样式表中的属性只能获取不能修改。

  • 如果想修改需要通过行间样式表修改,行间样式表的优先级最高,会覆盖内部样式表和外部样式表。

<body>
<div id="box1"></div>
<script type="text/javascript">
var box1 = document.getElementById("box1");
// alert(box1.currentStyle["width"]); //只支持IE浏览器
// alert(window.getComputedStyle(box1, null)["height"]); //支持ie浏览器外的其他浏览器
alert(getStyle(box1, "backgroundColor"));
/*
为了简化书写和兼容浏览器,一般封装一个方法出来
*/
function getStyle (obj, attributeName) {
    if(obj.currentStyle){    //如果存在对象,则是在ie浏览器
        return obj.currentStyle[attributeName];
    }else {    //其他浏览器
        return window.getComputedStyle(obj, null)[attributeName];
    }
}
</script>
</body>

补充:

offsetWidth、offsetHeight 可以获取宽和高,包括 borderpadding,其实是这个元素的实际占据的空间。但是只能获取不能修改

Copyright © 李振超 2018 all right reserved,powered by Gitbook
该文件最后修订时间: 2018-10-18 03:19:29

results matching ""

    No results matching ""