【问题标题】:jquery animate background-position - problem getting the current background position firstjquery animate background-position - 首先获取当前背景位置的问题
【发布时间】:2011-07-11 12:31:02
【问题描述】:

当用户单击按钮时,我正在尝试从元素的当前位置为元素的背景设置动画。我可以在第一次点击时执行此操作,但随后的点击失败。

这是我的代码...

var testme;

$(document).ready(function(){     
    $(".navleft").live("click", function() {
        testme = parseInt($(this).css("background-position").replace("% 0%", "").replace("px 0%", ""));
        $(this).parent().animate({backgroundPosition: (testme + 297) + "px"}, 500);
        $(this).parent().find("p").text(testme);
    });
});

编辑:

$(".navleft").live("click", function() {
    $(this).parent().animate({backgroundPosition: "+=297"}, 500);
});

如下所示,除非您使用的是 IE,否则它会在每次点击时重置为 0,然后再次动画。

这是我的意思的链接...http://jsfiddle.net/TdaSV/

解决方案(由于被推向正确的方向):

$(".navleft").live("click", function() {
    $(this).parent().animate({'background-position-x': '+=297'}, 500);
});

【问题讨论】:

    标签: javascript jquery jquery-animate background-position


    【解决方案1】:

    你应该先停止之前的动画,然后再开始一个新的:

    $(this).parent().stop(true, true).animate({backgroundPosition:...
    

    另外,如果您需要在当前背景位置添加 297 像素,则不需要读取当前位置,以下应该工作:

    $(this).parent().animate({backgroundPosition: "+=297"}, 500);
    

    see more examples in jquery website.

    【讨论】:

    • 这不是问题...我认为问题在于在第二次单击时设置 testme 变量。我认为我的替换不起作用,因为我正在尝试替换不存在的东西。
    • 嗯,奇怪的是在 IE 中不起作用:-/,如果你在 jsFiddler.net 中模拟它会更容易测试。
    猜你喜欢
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 2011-02-10
    • 2011-09-23
    • 1970-01-01
    相关资源
    最近更新 更多