2013-10-11 30 views
0

如果我有一个动画gif从左到右,我如何切换gif从右到左通过javascript?我有它的工作,但我不知道如何停止GIF并切换到另一个GIF从右到左。它只是从左到右循环相同的gif,然后回到左侧。反向gif是ani_catrev.gif。用javascript动画图片

<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Cat running</title> 
    <style type="text/css"> 
    #container { 
    background:url(catBack1200.jpg) no-repeat; 
    width:1200px; 
    height:440px; 
} 
#catbox { 
    position:absolute; 
    top:330px; 
    left:10px; 
} 
</style> 
<script type="text/javascript"> 
    var switchDirection = false; 
function doAnimation() { 
var catbox = document.getElementById("catbox"); 
var currentLeft = catbox.offsetLeft; 
var newLocation; 
if (switchDirection == false) 
{ 
newLocation = currentLeft + 5; 
if (currentLeft >= 1000) 
{ 
switchDirection = true; 
} 
} 
else 
{ 
newLocation = currentLeft - 5; 
if (currentLeft <= 0) 
{ 
switchDirection = false; 
} 
} 
catbox.style.left = newLocation + "px"; 
} 
</script> 
</head> 

<body onload="setInterval(doAnimation, 10)"> 
<div id="container"> 
<div id="catbox"> 
    <img src="ani_cat.gif" id="cat" width="100" height="60" alt="busy kitty" /> 
</div> 
</div> 
</body> 
</html> 
+0

您无法通过JS控制GIF。您可能会考虑使用多个GIF并让JS在它们之间切换。 – sushain97

+1

它的两个不同的GIF。我需要JS在它们之间切换。 – 2Truth

回答

2

你需要获得一个参考你的猫图片:

var catimg = document.getElementById("cat"); 

你可以把该行的代码的声明变种Catbox广告之下。接下来,代码你如果(switchDirection ==假)内的第一行应该是:

if (catimg.src != 'ani_cat.gif') catimg.src = 'ani_cat.gif'; 

和你switchDirection条款的其他部分中:

if (catimg.src != 'ani_catrev.gif') catimg.src = 'ani_catrev.gif'; 

这里的功能应该是什么样子:

function doAnimation() { 
    var catbox = document.getElementById("catbox"); 
    var catimg = document.getElementById("cat"); 
    var currentLeft = catbox.offsetLeft; 
    var newLocation; 

    if (switchDirection == false) 
    { 
     newLocation = currentLeft + 5; 
     if (catimg.src != 'ani_cat.gif') catimg.src = 'ani_cat.gif'; 

     if (currentLeft >= 1000) 
     { 
      switchDirection = true; 
     } 
    } 
    else 
    { 
     newLocation = currentLeft - 5; 
     if (catimg.src != 'ani_catrev.gif') catimg.src = 'ani_catrev.gif'; 

     if (currentLeft <= 0) 
     { 
      switchDirection = false; 
     } 
    } 

    catbox.style.left = newLocation + "px"; 
} 
+0

你能解释多一点,我得到语法错误...我拿出(switchDirection == false)? – 2Truth

+0

我更新了我的答案,为您提供了全面的功能。 – Jay

+0

或更好,请设置catimg.src设置switchDirection变量的位置。然后,您将不需要添加另一个if语句(这些语句在性能上是昂贵的)。 – Jay