<style type="text/css">
#box1 {
width: 200px;
height: 200px;
/* background: pink !important; */
background-color: pink;
}
#div {
width: 500px;
margin: 0 auto;
}
</style>
<div id="div">
<button id="btn01">点一下我变大</button>
<div id="box1">
</div>
<button id="btn02">点一下我 读取样式</button>
</div>
<script type="text/javascript">
window.onload = function () {
// 点击按钮后修改 box1 大小
// 获取box1
var box1 = document.getElementById('box1');
// 为按钮绑定单击响应函数
var btn01 = document.getElementById('btn01');
var btn02 = document.getElementById('btn02');
btn01.onclick = function () {
// 修改box1 的宽度
// 通过js修改元素样式
// 语法: 元素.style.样式名 = 样式值
// 注意:如果CSS的样式名 含有 - ,
// 这种名称在JS是不合法的 如: background-color
// 需要将注意的样式名修改为驼峰命名法,
// 去掉-,然后将-后面的首字母大写
// 我们通过style属性设置的样式都是内联样式,
// 而内联样式有较高的优先级,所以通过js修改的样式往往会立即显示
box1.style.width = "500px";
// box1.style.height = "500px";
// // box1.style.background = "yellow";
// box1.style.backgroundColor = "yellow";
}
// dom 操作只能增加 修改行内样式 所以开始行内没有样式的时候 无法获取到具体数据
btn02.onclick = function () {
// 读取box1的样式
console.log(box1.style.width);
// alert(box1.style.width)
}
}
</script>
浙公网安备 33010602011771号