<!DOCTYPE html>
<html lang="ch">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定时器的应用1</title>
<script>
window.onload = function () {
var btn = document.getElementById('btn');
var box = document.getElementById('box');
var timer;
btn.onclick = function () {
// 由于每点击一次就会开启一个定时器,所以每次都需要关闭前一个定时器
clearInterval(timer);
// 创建一个定时器
timer = setInterval(function () {
// 获取方块left初始值 parseInt()可以将字符串转换为数字,即获取有效值
var oldleft = parseInt(getStyle(box, 'left'));
// 赋予方块left新值
var newleft = oldleft + 10;
// 为方块left设置新值
box.style.left = newleft + 'px';
// 当到达1000px时停下
if (newleft > 1000) {
newleft = 1000;
}
if (newleft === 1000) {
clearInterval(timer);
}
}, 30);
};
// 定义一个获取元素样式的函数
function getStyle(obj, name) {
if (window.getComputedStyle) {
// 其他浏览器
return getComputedStyle(obj, name)[name];
} else {
// IE浏览器
return obj.currentStyle[name];
}
}
};
</script>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#clue {
width: 0;
height: 1000px;
border-left: solid black 1px;
position: absolute;
top: 0;
left: 1000px;
}
</style>
</head>
<body>
<button id="btn">使div向右移动</button>
<br><br>
<div id="box"></div>
<div id="clue"></div>
</body>
</html>
效果:
点击按钮后,红色方块向右移动,到达黑线后停止