//欢迎加我VX进群交流
vx账号:-Sep07
一、
固定语法:
元素.style.样式名 = "样式值";
如果CSS样式名中含有’-’,在JS中是不合法的
需要将该种样式名修改为驼峰命名法
background-color
改为backgroundColor
通过style属性设置的样式都是内嵌样式
而内嵌样式具有较高的优先级,所以通过JS修改的样式往往会立即显示
如果在样式表的样式中加上"!important"则该样式会具有最高的优先级
通过style属性也可以读取到的样式,但也只能读取到内嵌样式。不能读取样式表中的样式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#box1{
width: 200px;
height: 200px;
background-color: #FF6700;
}
</style>
<script>
window.onload = function(){
/*点击按钮后修改box1的大小*/
//获取box1
var box1 = document.getElementById("box1");
//为button绑定单击响应函数
var btn01 = document.getElementById("btn01");
btn01.onclick = function(){
//修改box1的宽度
box1.style.width = "400px";
box1.style.height = "400px";
box1.style.backgroundColor = "red";
};
//点击按钮2后“读取”元素的样式
var btn02 = document.getElementById("btn02");
btn02.onclick = function(){
//读取内嵌的元素的样式
alert(box1.style.width);
alert(box1.style.backgroundColor);
};
};
</script>
</head>
<body>
<button id="btn01">点我一下1</button>
<button id="btn02">点我一下2</button>
<br /><br />
<div id="box1"></div>
</body>
</html>
//欢迎加我VX进群交流
vx账号:-Sep07