定时器的简单应用动画,滑块的移动
<body>
<style>
* {
margin: 0;
padding: 0;
}
#box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
/* top: 0; */
}
</style>
<script>
window.onload = function () {
var box1 = document.getElementById("box1")
var btn1 = document.getElementById("btn1")
var timer
btn1.onclick = function () {
// var oldValue = box1.offsetLeft
//parseInt=> 解析一个字符串,并返回一个整数。 18px =>18
//关闭上一个定时器,防止连续点击时的叠加,clearInterval一次只能关闭一个定时器
clearInterval(timer)
timer = setInterval(function () {
var oldValue = parseInt(getStyle(box1, "left"))
var newValue = oldValue + 39
if(newValue > 800){
newValue= 800
}
box1.style.left = newValue + "px"
if (newValue == 800) {
clearInterval(timer)
}
}, 30)
}
}
/*
获取元素的样式
参数:
obj 要获取样式的元素
name 要获取的样式名
*/
function getStyle(obj, name) {
/* if (window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{ //IE8不兼容getComputedStyle
return obj.currentStyle[name]
} */
if (obj.currentStyle) {
return obj.currentStyle(name)
} else {
return getComputedStyle(obj, null)[name]
}
}
</script>
<button id="btn1">开始</button><br><br>
<div style="width: 0px; height: 1000px; border:1px red solid; position: absolute; left: 800px; "></div>
<div id="box1"></div>
</body>