1. 程式人生 > >javascript教程系列40:DOM中操作樣式的兩種方式

javascript教程系列40:DOM中操作樣式的兩種方式

AS color 單位 css 註意 pan col ntb javascrip

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‘;

javascript教程系列40:DOM中操作樣式的兩種方式