【问题标题】:changing an element's background using the CSS property使用 CSS 属性更改元素的背景
【发布时间】:2009-07-29 15:13:38
【问题描述】:

我有一个带背景的 div,我想在点击时更改背景的位置。

这是我的 jQuery sn-p :

$('#sprite').click(function () {
    $(this).css('backgroundPosition', '-40px');
});

虽然这工作正常,但我想通过“第二次”点击返回到原始位置,全部重置。

嗯,这就是所谓的“回调”吧?

我试过了,但是没有用:

$('#sprite').click(function () {
    $(this).css('backgroundPosition', '-40px');
},function () {
    $(this).css('backgroundPosition', '40px');
});

【问题讨论】:

    标签: jquery css toggle background-position


    【解决方案1】:

    您应该考虑为此使用“切换”功能...它允许您在 2 个不同的 CSS 类之间切换...查看本教程 here

    $('#sprite').click(function() {
       $(this).toggle(
          function(){
        $(this).css('backgroundPosition', '40px');
          }, 
          function () {
        $(this).css('backgroundPosition', '-40px');
        });
    });
    

    另一种选择而不是直接设置 CSS 属性是为您的背景创建一个 CSS 类并简单地切换该类。

    CSS

    <style type="text/css">
        .spritebg { background-position: -40px; }
    </style>
    

    jQuery

    ​​>
    $("#spite").click(function() {
       $(this).toggleClass("spritebg");
    });
    

    【讨论】:

    【解决方案2】:

    您误解了回调的概念。编程中的回调是在执行代码后立即调用的函数。

    在您的情况下,您是在说以下内容:

    点击时,将我的背景位置设置为 -40px。完成后,将其设置为 40px(立即撤消您的函数刚刚执行的操作)。

    在这种情况下,您不需要使用回调函数。您需要设置一个切换开关,以便当用户单击您的元素时,运行一个函数……然后当他们下次单击该元素时,运行第二个函数。

    【讨论】:

      【解决方案3】:

      用类来做。这要容易得多。

      <style type="text/css">
          #spite.moved {
              background-position: -40px;
          }
      </style>
      
      <script type="text/javascript">
          $(function () {
              $("#spite").click(function () {
                  $(this).toggleClass("moved");
              });
          });
      </script>
      

      【讨论】:

        猜你喜欢
        • 2017-02-26
        • 2013-03-05
        • 1970-01-01
        • 2019-03-05
        • 2022-10-07
        • 1970-01-01
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多