【问题标题】:jquery: Math failedjquery:数学失败
【发布时间】:2013-09-16 17:35:41
【问题描述】:

以下代码循环遍历精灵图像,每秒移动 -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/

【问题讨论】:

  • 请在您的问题中包含所有相关代码。

标签: jquery math logic


【解决方案1】:

正如 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);
});

【讨论】:

    【解决方案2】:

    很难弄清楚你在做什么。

    但也许你的意思是:

        if(thismarginLeft > -360){
    

    而不是这个:

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

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

        thismarginLeft = $this.css("margin-left").replace(/[^0-9\-]/g,'');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多