- 内联样式
<script type="text/javascript">
/**
*
* 修改box1的宽度
* 通过js修改元素的样式
* 元素.style.样式名 = 样式值
*
* 通过style属性设置的样式都是内联样式
* 而内联样式有较高的优先级,所以通过js修改的样式往往会立即显示
*
* 如果在样式表中写了!important, 则此时样式忽悠最高的优先级
* 即使通过js也不能覆盖
* */
var box = document.getElementById("box");
var btn = document.getElementById("btn");
btn.onclick = function () {
box.style.width = "300px";
//css 样式名中如果含有-
//需要将这种样式名修改为驼峰命名法
box.style.backgroundColor = "yellow";
}
// 读取内联样式
console.log(box.style.width);//300px
</script>
- 浏览器当前样式的兼容问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
window.onload = function () {
/**
* 获取元素当前显示的样式
* 元素.currentStyle.样式名
*
* 如果当前元素没有设置该样式,则获取它的默认值
* 只有IE浏览器支持,其他的浏览器不支持
* */
var box1 = document.getElementById("box1");
// alert(box1.currentStyle.width);
/**
* 其他浏览器中可以使用
* getComputedStyle()
* 此方法为window的方法,可以直接使用
* 需要两个参数:
* 第一个,要获取样式的元素
* 第二个:可以传递一个为元素,一般都传null
*
* 该方法会返回一个对象,对象中封装了当前元素对应的样式
* */
var obj = getComputedStyle(box1,null);
alert(getComputedStyle(box1,null).width);
};
function getStyle(obj, name) {
// if (getComputedStyle)
/**
* 由于Ie中不存在此方法,如果通过变量getComputedStyle的形式
* 则控制台报错
*
* 如果通过属性(window.getComputedStyle)的方式
* 则会提示未定义
* */
if (window.getComputedStyle){
//正常浏览器的方式,
return getComputedStyle(obj, null)[name];
} else{
//IE8的方式,没有getComputedStyle方法
return obj.currentStyle[name];
}
}
</script>
<style type="text/css">
#box1{
width: 100px;
height: 100px;
background-color: #000;
}
</style>
</head>
<body>
<div id="box1" style="width: 200px; background-color: gray;">
</div>
</body>
</html>