javascript总结40:DOM中操作样式的两种方式

时间:2024-05-08 08:37:49

1 DOM中操作样式的两种方式

1 通过元素的style属性

注意: 通过style属性设置样式时,css中要写单位的属性,在js代码中也要加单位

//html
<div id="box"></div> //js
var box = document.getElementById('box');
box.style.width = '100px';
box.style.height = '100px';
box.style.backgroundColor = 'red'; <div id="box" style="width:100px; height:100px; background-color:red">

2 通过元素的className属性

//html
<div id="box"></div> //css
.show{
width:100px;
height:100px:
background-color:red;
} //js
var box = document.getElementById('box');
box.className = 'show';