What I want to do is image to move right when mouse hovers over it and come back to the same position when mouse is taken off the image. But what this is doing is the image goes to the left and disappears when mouse hovers over it. Please tell me what my mistake is.

<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>
有帮助吗?

解决方案

jQuery's animate() animates CSS properties, so you should probably stick with animating the same property, as left and right are two different CSS properties

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

Also note that in some cases you have to set an inital value in CSS, as jQuery can't compute default values like inherit or auto, and that setting left and top values doesn't work without a position

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

FIDDLE

其他提示

The code needs to be wrapped in $(document).ready(). It is executing before the elements are loaded on the DOM. $(document).ready(function(){}) tells jQuery to wait until the DOM is loaded before executing your script.

$(document).ready(function(){
   $('#box img').hover(
      function () {
        $(this).animate({
          right: '2px'
        });
      }, 
      function () {
        $(this).animate({
          left: '2px'
        });
      }
    );
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top