這兩者都是:獲取計算後的樣式,也叫當前樣式、終於樣式,具體區分如下:
window.getComputedStyle(element[,pseudo-element]);
首先是有兩個參數,元素和僞類。第二個參數不是必須的,當不查詢僞類元素的時候可以忽略或者傳入 null
。只讀,DOM下方法
elem.currentStyle;IE8下兼容的方法;
和Style相比
element.style
讀取的只是元素的“內聯樣式”,即 寫在元素的 style 屬性上的樣式;而 getComputedStyle
讀取的樣式是最終樣式,包括了“內聯樣式”、“嵌入樣式”和“外部樣式”。
element.style
既支持讀也支持寫,我們通過 element.style
即可改寫元素的樣式。而 getComputedStyle
僅支持讀並不支持寫入
因爲是隻讀的,所以:讀樣式,用getComputedStyle(elem),設置樣式用elem.style.屬性=
網頁右下角小廣告彈出框——小案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>窗口右下角消息彈出框</title>
<style>
* {
margin: 0;
padding: 0;
}
.msg {
width: 200px;
height: 200px;
position: fixed;
right: 30px;
bottom: -200px;
background-color: LightBlue;
}
.msg>a {
float: right;
padding: 5px 10px;
border: 1px solid black;
cursor: pointer;
}
.msg>a:hover {
background-color: lightseagreen;
}
</style>
</head>
<body>
<div class="msg" id="msg">
<a onclick="adv.moveDownStep()">X</a>
<h1 style="line-height: 200px;text-align: center;">我是小蘋果</h1>
</div>
</body>
<script>
var adv = {
div:null,
step:5,//每步長5px
interval:20,//時間間隔
init:function(){
this.div = document.getElementById("msg");
adv.moveUpStep();
},
//兼容低版本的ie
brow: function () {
var brosor = navigator.userAgent;
var divStyle;
if(brosor.indexOf("MSIE")==-1){
divStyle = getComputedStyle(this.div);//DOM
}else {
divStyle = this.div.currentStyle;//IE8
}
return divStyle;
},
moveUpStep:function(){
var stylediv = parseInt(this.brow().bottom)+this.step;
this.div.style.bottom = stylediv+"px";
if (stylediv<0){
timer = setTimeout(function(){
adv.moveUpStep();
},this.interval);
}
},
moveDownStep: function () {
clearTimeout(timer);
timer = null;
var stylediv = this.brow();
var divbottom = parseInt(stylediv.bottom);
this.div.style.bottom = divbottom-this.step+"px";
var divHeight = parseInt(stylediv.height);
if(divbottom>-divHeight){
timer1 = setTimeout(function () {
adv.moveDownStep();
},this.interval);
}else { //如果到底,等一段時間後,自動調用moveUpStep
clearTimeout(timer1);
timer1 = null;
timer = setTimeout(function () {
adv.moveUpStep();
},2000);
}
}
}
adv.init();
</script>
</html>