0

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

   <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>
4

1 回答 1

2

您需要获取对您的猫图像的引用:

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

您可以将该行代码放在 var catbox 的声明下。接下来,您的 if (switchDirection == false) 中的第一行代码应该是:

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

在你的 switchDirection 子句的 else 部分中:

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";
}
于 2013-10-11T16:47:34.183 回答