![](/img/trans.png)
[英]How to make an outside div come from left on click and on ri-click go to right with jQuery toggle and animation?
[英]How do I make a div go left and then right in javascript? (no jQuery)
这应该很简单,但是我想没有jQuery会使它有点困难。
我想重复一个过程,其中div向右移动100px(带有动画),然后向左移动100px(所以我想要连续移动)。
这个问题似乎有很多jQuery答案,但没有纯javascript解决方案。 我可能在这里缺少明显的东西,但我找不到。
这是代码:
var left = 0;
var id = setInterval(function(){goRight()}, 10);
var ed = setInterval(function(){goLeft()}, 10);
function goRight(){
var redpixel = document.getElementById("redpixel");
left++;
redpixel.style.left = left + "px";
if (left>100) {
clearInterval(id)
goLeft();
}
}
function goLeft(){
var redpixel = document.getElementById("redpixel");
left-=1;
redpixel.style.left = left + "px";
if (left<100) {
clearInterval(ed);
goRight()
}
}
HTML:
<button onclick="goRight()">Go Right</button>
<div id="redpixel"></div>
CSS:
.container {
width: 480px;
height: 800px;
border: 1px solid black;
}
#redpixel {
position: absolute;
top: 200px;
left: 0;
background: red;
width: 25px;
height: 25px;
}
最后评论:
感谢所有帮助,谢谢!
代码的问题在于,您同时设置了左右动画,并且由于left<100
所以立即清除了左动画。 固定代码:
var left = 0, id = setInterval(goRight, 10); ed; function goRight() { var redpixel = document.getElementById("redpixel"); left++; redpixel.style.left = left + "px"; if (left > 100) { clearInterval(id); ed = setInterval(goLeft, 10); } } function goLeft() { var redpixel = document.getElementById("redpixel"); left -= 1; redpixel.style.left = left + "px"; if (left < 1) { clearInterval(ed); id = setInterval(goRight, 10); } }
#redpixel { position: absolute; top: 50px; left: 0; background: red; width: 25px; height: 25px; }
<div id="redpixel"></div>
还有一点,正如Adjit所展示的,将CSS方法视为更简单,更有效的做法确实有意义。
实际上,您根本不需要任何JavaScript,而使用CSS3则非常简单。
只需要像这样设置关键帧和动画:(显然包括必要的浏览器兼容性)
#box {
height: 100px;
width: 100px;
background: red;
position: relative;
animation: waver 2s infinite;
-webkit-animation: waver 2s infinite;
}
@keyframes waver {
0% {left: 0px;}
50% {left: 100px;}
100% {left: 0px;}
}
@-webkit-keyframes waver {
0% {left: 0px;}
50% {left: 100px;}
100% {left: 0px;}
}
有关示例,请参见此提琴: http : //jsfiddle.net/bwsd3eoy/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.