注意obj.timer =setInterval()这个用法。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#run{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="run"></div>
</body>
</html>
<script>
function $(id){return document.getElementById(id)}
$("btn200").onclick = function () {
animate($("run"),200);
}
$("btn400").onclick = function () {
animate($("run"),400);
}
function animate(obj,target){
obj.timer = setInterval(function(){
if(obj.offsetLeft > target){
clearInterval(obj.timer);
}
obj.style.left = obj.offsetLeft + 10 + "px";
},30);
}
</script>
元素动画实现
本文介绍了一个简单的HTML页面,其中包含按钮和可移动的div元素。通过JavaScript实现了div元素根据按钮点击的不同,以不同速度进行水平移动的动画效果。
705

被折叠的 条评论
为什么被折叠?



