如图所示,本次想做盒子的定时移动,第一个盒子以每50ms,第二三个盒子以每10ms向左移动一个像素。
样式上需将盒子绝对定位,以便后续能改变盒子的left值使其移动。
javascript上需监听其offsetleft值,并通过left修改其位置。
注意一般情况下clearInterval都写在setInterval中,以便定时检测是否达到取消定时器的条件。
代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
.w{
width: 100px;
height: 60px;
margin-top: 20px ;
position:absolute;
left: 0;
}
.one{
background-color: aqua;
top: 20px;
}
.two{
background-color: aquamarine;
top: 100px;
}
.three{
background-color: #00FFFF;
top: 180px;
}
</style>
</head>
<body>
<div class="one w">1</div>
<div class="two w">2</div>
<div class="three w">3</div>
<script>
var one=document.querySelector('.one');
var two=document.querySelector('.two');
var three=document.querySelector('.three');
var time=setInterval(function(){
one.style.left=one.offsetLeft+1+'px';
if(one.offsetLeft>=400){
clearInterval(time);
}
},30);
function kind(ele,tim){
var timer=setInterval(function(){
ele.style.left=ele.offsetLeft+1+'px';
/*ele.offsetLeft>=400 ele.style.left>='400px' */
if(ele.offsetLeft>=400){
clearInterval(timer);
}
},tim);
}
kind(two,10);
kind(three,10);
</script>
</body>
</html>
问题
ele.style.left>=‘400px’
不知道此不等式哪里有问题。。
按理来说如果一开始有通过行内样式给left赋值,后期应该能通过ele.style.left查询到其值。。。