jQuery悬停在不正常工作

时间:2014-01-19 23:14:12

标签: javascript jquery html jquery-animate jquery-hover

我想要做的是当鼠标悬停在图像上时图像向右移动,当鼠标从图像上移开时返回到相同位置。但是这样做的是图像向左移动并在鼠标悬停在图像上时消失。请告诉我我的错误。

<html>
  <head>
    <style>
      img { position: relative; 
      }
    </style>

    <script src="http://code.jquery.com/jquery-1.10.2.min.js" type = "text/javascript"></script>
    <script type = "text/javascript">
    $('#box img').hover(
      function () {
        $(this).animate({
          right: '2px'
        });
      }, 
      function () {
        $(this).animate({
          left: '2px'
        });
      }
    );
    </script>
  </head>

  <body>
    <div id = "box">
      <img src="pathtimage/1.jpg" hspace="30"  height="350" width="220" >
    </div>
  </body>
</html>

2 个答案:

答案 0 :(得分:4)

jQuery的animate()为CSS属性设置了动画,因此您应该坚持使用相同属性的动画,因为leftright是两个不同的CSS属性

$(function() {
    $('#box img').hover(function () {
        $(this).animate({
            left: '2px'
        }, 600);
    }, function () {
        $(this).animate({
            left: '0px'
        }, 600);
    });
});

另请注意,在某些情况下,您必须在CSS中设置初始值,因为jQuery无法计算inheritauto等默认值,并且设置左值和顶值不会没有职位的工作

#box img {position: relative; left: 0}

FIDDLE

答案 1 :(得分:1)

代码需要包装在$(document).ready()中。它在元素加载到DOM之前执行。 $(document).ready(function(){})告诉jQuery在执行脚本之前等待DOM加载。

$(document).ready(function(){
   $('#box img').hover(
      function () {
        $(this).animate({
          right: '2px'
        });
      }, 
      function () {
        $(this).animate({
          left: '2px'
        });
      }
    );
});