我一直在研究一个非常简单的动画脚本。图片在点击时移动,再次点击时停止,等等。我有这一切工作正常。麻烦的是,我在图像下面停止了所有按钮,这些按钮不仅会停止图像,还会将图像返回到原始位置。到目前为止,它停止,但它不会返回。将动画图像返回原位
我已经搜索并找到了几种不同的解决方案,但是这是一项大学任务,我不允许使用Jquery。
这是我的脚本:
var timer = null;
var cat = null;
var dog = null;
function moveOver1Pixel()
{
cat.style.left = parseInt(cat.style.left) + 1 + "px";
}
function moveOver10Pixels()
{
dog.style.left = parseInt(dog.style.left) + 10 + "px";
}
window.onload=function()
{
//MOVE CAT FUNCTION
cat = document.getElementById("cat");
cat.onclick=function(){
if(timer == null)
{
timer = setInterval("moveOver1Pixel();", 100);
}else{
clearInterval(timer);
timer = null;
}
}
// MOVE DOG FUNCTION
dog = document.getElementById("dog");
dog.onclick=function(){
if(timer == null)
{
timer = setInterval("moveOver10Pixels();", 30);
}else{
clearInterval(timer);
timer = null;
}
}
// STOP BUTTON FUNCTION
document.getElementById("stop").onclick=function()
{
window.clearInterval(timer);
timer = null;
reset = true;
}
}
,这是我使用的HTML部分:
<img src="cat.jpg" id="cat" style="height:100px;position:absolute;left:10px">
<img src="dog.jpg" id="dog" style="height:100px;position:absolute;left:10px;top:110px">
<input type="button" value="EVERYONE STOP" id="stop" style="position:absolute;left:10px;top:220px">
我觉得解决我的问题应该是简单的......什么我m缺少按钮的onclick函数?或者我将不得不创建一个全新的函数来重置/返回图像到原来的位置?
在停止功能中,您需要将style.left设置为0或将其删除。现在你只是停止运动。 – tenub
不知道如果你想动画返回开始或立即,所以我把动画的评论。我改变了很多风格来帮助你学习 –