这两者都是:获取计算后的样式,也叫当前样式、终于样式,具体区分如下:
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>