您的位置:首页 > Web前端 > JavaScript

JavaScript 高级课程之定时器setInterval,clearInterval

2016-06-08 14:11 573 查看
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript 高级课程之定时器setInterval,clearInterval</title>
<style>
#div1 { width:100px; height:100px; background-color:#005812; position:absolute}
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById('div1');
var oInp = document.getElementById('inp1');
var timer = null;
oInp.onclick = ac;

function ac(){
clearInterval(timer); //先关后开,防止重复定时器
timer = setInterval(function (){
if(oDiv.offsetLeft >= 300){
clearInterval(timer);
}else{
oDiv.style.left = oDiv.offsetLeft + 1 +'px';
}
},30)
}
}
</script>
</head>
<body>
<input type="button" value="移动" id="inp1"/>
<div id="div1"></div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: