如何通过使用间隔更改jquery中的背景位置来制作此自定义动画

how to make this custom animation by changing background position in jquery using intervals?

本文关键字:位置 背景 动画 自定义 何通过 jquery      更新时间:2023-09-26

我正试图通过移动div上作为背景的图像的背景位置(帧)来制作一个小动画。我正在使用Jquery来制作这个动画。我在背景图像上有6帧,第一帧从0,0px开始,第二帧从85px开始,0,第三帧在172px,0,依此类推。我想在这些帧之间转换,直到单击"停止"为止。我的jquery代码粘贴在下面。我已经制作了一个像素移动的数组。我希望每帧保持1000毫秒,然后过渡到下一帧。我哪里出了问题,但不知道在哪里。。这是我的代码

$(document).ready(function () {
    var timer;
    $("#clickMe").click(function() {
        //alert("you are here");
        timer=setInterval(moveframe,1000);
    });
    $("#stop").click(function() {
        clearInterval(timer);
    });
});
function moveframe() {
    var framespx=[0,85,172,256,512,1024];
    for (var i=0;i<framespx.length;i++) {
        alert("you ar here");
        var xPos=framespx[i]+"px ";
        var yPos="0px";
        $('.fixed').css({backgroundPosition: xPos+yPos});
    }
}

您的代码看起来有一些逻辑错误,运行您的代码,可以看到相同的背景。

尝试:

$(document).ready(function () {
    var timer;
    $("#clickMe").click(function() {
    //alert("you are here");
        timer=setInterval(moveframe,1000);
    });
    $("#stop").click(function() {
        clearInterval(timer);
    });
});
var j=0;
function moveframe() {
    var framespx=[0,85,172,256,512,1024];
    for (var i=0;i<framespx.length;i++) {
        if (j%framespx.length == i){
            alert("you ar here");
            var xPos=framespx[i]+"px ";
            var yPos="0px";
            $('.fixed').css({backgroundPosition: xPos+yPos});
            j++
            break;
        }
    }
}
 css({'background-position': xPos+' '+yPos});

好吧,上面的属性值对我来说有点困惑,希望这是正确的,但有更多的保证;

css('background-position-x', xPos);
css('background-position-y', yPos);

现在我不认为for循环在这里是强制性的

var posAry=[0,85,172,256,512,1024];
var currPos=0;
var timer;
$(document).ready(function () {
    $("#start").click(function() {       
      timer=setInterval(move,1000);        
   });
   $("#stop").click(function() {
     clearInterval(timer);
   });
});

function move() {  
  $('.fixed').css({'margin-left': posAry[currPos]+'px' }); /**you can change it to background postion/padding/... as needed by you**/
  currPos++;
  if(currPos==(posAry.length))
    currPos=0; // for looping back
}

http://jsfiddle.net/7PvwN/1/