0

以下代码循环遍历精灵图像,每秒移动 -120,但由于某种原因,它从 0 跳转到 -120,然后跳转到 120 而不是 -240

    thismarginLeft = $this.css("margin-left").replace(/[^0-9]/g,'');
    if(thismarginLeft < -360 || thismarginLeft == 0){
            thismarginLeft = thismarginLeft - 120;
            if(thismarginLeft < -360){
              thismarginLeft = 0;
            }
    }

http://jsfiddle.net/FDRmv/1/

4

2 回答 2

3

正如 yahermann 所说,问题来自替换方法,该方法正在删除左边距 css 前面的“-”。

如果您不想使用“replace”,您甚至可以使用“parseInt”:(此处示例:http: //jsfiddle.net/FDRmv/2/

var internalMiniPoster;
$(".miniPosterImg").hover(function () {
    var $this = $(this);
    internalMiniPoster = setInterval(function () {
        thismarginLeft = parseInt($this.css("margin-left"),10); // always use a radix
        if (thismarginLeft < -360 || thismarginLeft == 0) {
            thismarginLeft = thismarginLeft - 120;
            if (thismarginLeft < -360) {
                thismarginLeft = 0;
            }
        }
        $this.css("margin-left", thismarginLeft + "px");
    }, 1000);
}, function () {
    clearInterval(internalMiniPoster);
});
于 2013-09-16T17:57:38.363 回答
1

很难弄清楚你在做什么。

但也许你的意思是:

    if(thismarginLeft > -360){

而不是这个:

    if(thismarginLeft < -360 || thismarginLeft == 0){

并且,包括 - 在你的正则表达式中:

    thismarginLeft = $this.css("margin-left").replace(/[^0-9\-]/g,'');
于 2013-09-16T17:50:51.533 回答