Div 定时移动

时间:2023-12-16 22:29:02
 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
</head>
<style>
button{width:80px; height:50px; margin: 10px;}
#divRed{width: 100px; height: 100px; background-color: red; position: absolute; top:90px; left: 0; }
</style>
<body>
<button type="text" id="btnLeft">左移动</button>
<button type="text" id="btnRight">右移动</button>
<div id="divRed"></div>
<script type="text/javascript" charset="utf-8">
$(function(){
var btnL = $('#btnLeft');
var btnR = $('#btnRight');
var divR = $('#divRed');
btnL.click(function(){
MoveDiv(divR,'left',10,0)
});
btnR.click(function(){
MoveDiv(divR,'left',10,500)
});
function MoveDiv(obj,pos,dir,targer){
dir=parseInt(obj.css(pos)) < targer ? dir: -dir;
clearInterval(obj.timer)
obj.timer=setInterval(function(){
var speed=parseInt(obj.css(pos))+dir;
console.log(obj,pos);
if(speed > targer && dir > 0 || speed < targer && dir < 0 ){ speed = targer;}
obj.css(pos,speed +'px');
if(speed== targer){ clearInterval(obj.timer)} },30); } })
</script>
</body>
</html>