【问题标题】:jQuery mouseover mouseout opacityjQuery mouseover mouseout 不透明度
【发布时间】:2023-03-11 16:04:01
【问题描述】:
    function hoverOpacity() {
    $('#fruit').mouseover(function() {
        $(this).animate({opacity: 0.5}, 1500);
      });
    $('#fruit').mouseout(function() {
        $(this).animate({opacity: 1}, 1500);
      });
}

这是我为div#fruit 设置动画的函数,它确实有效。

问题是这样的;当你在mousein 动画结束之前mouseout 时,它必须在开始mouseout 之前完成动画。 (希望这是有道理的)

这通常不会引起注意,但持续时间较长时会引起注意。

我希望动画停止并反转到原始状态,而不是完成动画。

【问题讨论】:

标签: jquery mouseover opacity mouseout


【解决方案1】:

您正在寻找stop 函数,后面可能跟着show(或hide,或css,取决于您希望opacity 最终处于什么状态)。

function hoverOpacity() {
    $('#fruit').mouseover(function() {
        $(this).stop(true).animate({opacity: 0.5}, 1500);
      });
    $('#fruit').mouseout(function() {
        $(this).stop(true).animate({opacity: 1}, 1500);
      });
}

true 告诉动画跳到结尾。如果这是元素上唯一的动画,那应该没问题;否则,正如我所说,您可以查看 css 以明确设置所需的不透明度。

不过,另外,您可能会考虑使用 mouseentermouseleave 而不是 mouseovermouseout,原因有两个:1. mouseover 在鼠标移过元素时重复,以及 2. mouseovermouseout bubble,所以如果你的“fruit”元素有子元素,你也会收到来自它们的事件,这往往会破坏这种动画的稳定性。 p>

【讨论】:

  • @a-second-mix:另请参阅关于可能为此使用不同事件的说明。
【解决方案2】:

也试试这个:

function hoverOpacity() {
    $('#fruit').hover(function() {
        $(this).animate({opacity: 0.5}, 1500);
    }, function() {
        $(this).animate({opacity: 1}, 1500);
    });
}

【讨论】:

    【解决方案3】:

    您需要在制作动画之前添加对.stop() 的调用以清除当前和任何排队的动画:

    function hoverOpacity() {
        $('#fruit').mouseover(function() {
            $(this).stop(true).animate({opacity: 0.5}, 1500);
          });
        $('#fruit').mouseout(function() {
            $(this).stop(true).animate({opacity: 1}, 1500);
          });
    }
    

    【讨论】:

      【解决方案4】:

      试试这个:

      function hoverOpacity() {
          $('#fruit').mouseover(function() {
              $(this).stop(true, true).animate({opacity: 0.5}, 1500);
            });
          $('#fruit').mouseout(function() {
              $(this).stop(true, true).animate({opacity: 1}, 1500);
            });
      }
      

      这应该会停止动画,清除队列(第一个参数)并跳转到最后(第二个参数),您可以根据需要更改/弄乱参数。

      【讨论】:

        猜你喜欢
        • 2011-03-03
        • 1970-01-01
        • 2013-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-15
        • 2014-03-09
        • 1970-01-01
        相关资源
        最近更新 更多