Javascript 将gif反转为另一个gf的动画
我有一张猫从左向右跑的动画gif,然后转身从右向左跑。似乎我的代码中的所有内容都是正确的。在我把代码复杂化之前,它似乎工作得很好,但是在移动时gif被冻结了。现在我已经修改了我的代码,但是现在gif并没有与另一个gif相反。它只是从左向右运行,然后向后运行。我似乎在我的代码中找不到任何错误。有人能帮忙吗Javascript 将gif反转为另一个gf的动画,javascript,Javascript,我有一张猫从左向右跑的动画gif,然后转身从右向左跑。似乎我的代码中的所有内容都是正确的。在我把代码复杂化之前,它似乎工作得很好,但是在移动时gif被冻结了。现在我已经修改了我的代码,但是现在gif并没有与另一个gif相反。它只是从左向右运行,然后向后运行。我似乎在我的代码中找不到任何错误。有人能帮忙吗 <html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="
<html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</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 catimg = document.getElementById("cat");
var currentLeft = catbox.offsetLeft;
var newLocation;
if (switchDirection == false)
{
newLocation = currentLeft + 3;
catimg.src == "ani_cat.gif";
if (currentLeft >= 600)
{
switchDirection = true;
}
}
else
{
newLocation = currentLeft - 3;
catimg.src == "ani_cat_rev.gif";
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>
测试
#容器{
背景:url(catBack1200.jpg)不重复;
宽度:1200px;
高度:440px;
}
#猫箱{
位置:绝对位置;
顶部:330px;
左:10px;
}
var开关方向=假;
函数doAnimation(){
var catbox=document.getElementById(“catbox”);
var catimg=document.getElementById(“cat”);
var currentLeft=catbox.offsetLeft;
var新定位;
if(switchDirection==false)
{
newLocation=currentLeft+3;
catimg.src==“ani_cat.gif”;
如果(currentLeft>=600)
{
开关方向=真;
}
}
其他的
{
newLocation=currentLeft-3;
catimg.src==“ani_cat_rev.gif”;
如果(当前左)
这里可能有个问题:在设置图像时,您使用了相等运算符==
而不是=,使用“=”而不是“==”,我想这可能是打字错误
不要在每个动画上都设置src,而是在切换时设置:
if (switchDirection == false) {
newLocation = currentLeft + 3;
if (currentLeft >= 600) {
catimg.src = "ani_cat_rev.gif";
switchDirection = true;
}
} else {
newLocation = currentLeft - 3;
if (currentLeft <= 0) {
catimg.src = "ani_cat.gif";
switchDirection = false;
}
}
if(switchDirection==false){
newLocation=currentLeft+3;
如果(currentLeft>=600){
catimg.src=“ani_cat_rev.gif”;
开关方向=真;
}
}否则{
newLocation=currentLeft-3;
如果(currentLeft)第一次运行,但循环时它会向后运行,不会来回运行。我在JSFIDLE中测试了两个动画图像,效果很好。可能图像加载需要时间。请尝试增加动画间隔。您是否有针对该问题的演示运行?
if (switchDirection == false) {
newLocation = currentLeft + 3;
if (currentLeft >= 600) {
catimg.src = "ani_cat_rev.gif";
switchDirection = true;
}
} else {
newLocation = currentLeft - 3;
if (currentLeft <= 0) {
catimg.src = "ani_cat.gif";
switchDirection = false;
}
}