javascript - jQuery 悬停在上方无法正常工作

标签 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>

最佳答案

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

关于javascript - jQuery 悬停在上方无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21223947/

相关文章:

html - 如何让iframe根据内容大小进行收缩和排行?

javascript - Bootstrap 下拉菜单 - 仅复选框选择而不选择文本

javascript - 在 JavaScript 中使用 async 时,then 函数内的函数参数的用途是什么?

javascript - 如何在 react-bootstrap 中更改我的 5 个选项卡之一的颜色?

javascript - jQuery 不适用于动态生成的相同 div

javascript - 使用 jQuery 操作 <body>? (或想出更好的解决方案)

jquery - 将字符串值传递到 animate Jquery 函数时出现问题

jquery - Canvas 外菜单的溢出与视差冲突

jquery - 根据页面位置更改背景颜色

html - 将 angularJS $index 传递给 onchange