代码之家  ›  专栏  ›  技术社区  ›  user818700

在jQuery悬停时移动div背景位置

  •  0
  • user818700  · 技术社区  · 13 年前

    我正试图让它发挥作用,但由于某种未知的原因,图像没有变化。。看看我创建的JSfiddle here 。(当你悬停在图像上时,图像应该会跳跃,当你悬停时,图像会向下浮动)。

    $(document).ready(function() {
      $('#hover-image').hover(
    
        function() {
          // Over
          $(this).animate({
            'background-position': 'center top'
          }, 5000);
        },
        function() {
          // Out
          $(this).animate({
            'background-position': 'center center'
          }, 5000);
        }
      );
    });
    #hover-image {
      width: 300px;
      height: 300px;
      background: url(http://icons.iconarchive.com/icons/artbees/paradise-fruits/256/Banana-icon.png);
      background-repeat: no-repeat;
      background-position: center center;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <div id="hover-image"></div>

    编辑:我现在发现你不能在非数字css值上设置动画。将背景位置更改为使用百分比解决了问题。

    2 回复  |  直到 13 年前
        1
  •  4
  •   Samuel Liew cicero lopes    13 年前

    不能为非数字CSS属性设置动画:

    这个 .animate() 方法允许我们在任何 数字 CSS属性。

    资料来源: http://api.jquery.com/animate/

        2
  •  3
  •   Andrey Shatilov    13 年前

    看看这个插件 http://keith-wood.name/backgroundPos.html - 一个jQuery插件,允许对背景图像的位置进行动画处理。

    i update jsfiddle

    $(document).ready(function(){
        $('#hover-image').hover(
    
            function(){
                // Over
                $(this).animate({backgroundPosition: '50% 100%'},500);              
            },
            function(){
                // Out
                $(this).animate({backgroundPosition: '50% 50%'},500);             
            }
        );
    });