
HTML
<div class="container">
<div id="box" class="box">
<div class="btns">
<button onclick="getStyle()">Get Style</button>
<button onclick="setStyle()">Set Style</button>
<button onclick="default_style()">Default Style</button>
</div>
</div>
<div class="box"></div>
</div>
JS
var box = document.getElementById('box');
function getStyle() {
var background_color = window.getComputedStyle(box, null).getPropertyValue("background-color");
var width = window.getComputedStyle(box, null).getPropertyValue("width");
var height = window.getComputedStyle(box, null).getPropertyValue("height");
alert("width: "+width + '\n' + "height: "+height + '\n' + "background-color: "+background_color)
}
function setStyle() {
box.style.width = 330 + 'px';
box.style.height = 100 + 'px';
box.style.backgroundColor = 'rgb(239, 248, 255)';
box.style.borderColor = 'blue';
for (var i=0; i<3; i++) {
document.getElementsByTagName('button')[i].style.backgroundColor = 'blue'
}
}
function default_style() {
box.style.width = 400 + 'px';
box.style.height = 200 + 'px';
box.style.backgroundColor = 'rgb(254, 244, 235)';
box.style.borderColor = 'orangered';
for (var i=0; i<3; i++) {
document.getElementsByTagName('button')[i].style.backgroundColor = 'orangered'
}
}
getComputedStyle方法給出應(yīng)用活動樣式表后的元素的所有CSS屬性的值,返回CSSStyleDeclaration表示一個(gè)css屬性鍵值對的集合,getPropertyValue是其的方法之一,返回屬性值,以下示例返回的就是屬性值
例
var style1 = getComputedStyle(target, null).getPropertyValue('background-color');
alert()中換行 +'\n'+
這個(gè)函數(shù)寫的好,這樣簡單了好多
function css(obj, attr, value)
{
switch (arguments.length)
{
case 2:
if(typeof arguments[1] == "object")
{ //二個(gè)參數(shù), 如果第二個(gè)參數(shù)是對象, 批量設(shè)置屬性
for (var i in attr)obj.style[i] = attr[i]
}
else
{ //二個(gè)參數(shù), 如果第二個(gè)參數(shù)是字符串, 讀取屬性值
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
}
break;
case 3:
//三個(gè)參數(shù), 單一設(shè)置屬性
obj.style[attr] = value;
break;
default:
alert("參數(shù)錯(cuò)誤!")
}
}