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

时间:2013-08-23 08:37:48

标签: javascript jquery css

我正试图让这个工作,但由于一些未知的原因,图像没有动摇。看看我创建的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 个答案:

答案 0 :(得分:4)

您无法为非数字CSS属性设置动画:

  

.animate()方法允许我们在任何数字 CSS属性上创建动画效果。

     

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

答案 1 :(得分:3)

查看此插件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);             
        }
    );
});
相关问题