【问题标题】:FadeIn() breaks CSS hover functionalityFadeIn() 中断 CSS 悬停功能
【发布时间】:2016-08-25 14:06:58
【问题描述】:

为什么 jQuery 的 .fadeIn() 函数会破坏我的 CSS 悬停功能?当您将鼠标悬停在它上面时,我的 div 应该显示它的菜单。当我的页面显示我将使菜单淡入时,它应该具有我的常规悬停功能。

这个JSFiddle很好地说明了这个问题。

为什么它会破坏我的悬停功能?如何同时保留淡入和悬停功能?

注意我需要保留 display: flex 以确保菜单 div 比其父 div 宽时不会换行。

.widget {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: #ddd;
}
.widget-menu {
  width: 400px;
  height: 100px;
  background-color: #555;
  position: absolute;
  top: 0;
  display: none;
}
.widget:hover .widget-menu {
  display: flex;
  /* used to ensure wrapping doesn't occur if the menu is wider than the widget container */
}
.widget:enabled .widget-menu {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
  <div class="widget-menu">
    <button>Btn 1</button>
  </div>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <p>Hover me to see menu appear. Then click the below button. Now my hovering is screwed up after the animation is complete.</p>
</div>

<br/>
<button>Fade In</button>

【问题讨论】:

  • 你到底想达到什么目的?菜单在淡入时可见,因此当您将鼠标悬停在文本上时,它已经显示了您喜欢的内容,对吧?
  • @Roberrrt 在页面加载时菜单将淡入,因此用户知道它在那里。然后在第一次悬停和悬停/鼠标离开后,该菜单应该像往常一样消失。现在那没有发生
  • 哦,这是因为 jQuery 为您的元素添加了内联样式,从而推翻了您的悬停

标签: jquery css


【解决方案1】:

你需要用 flex 激活fadeIn

$('.widget-menu').css('display', 'flex').hide(); // do this on doc ready or before you call the fadeIn

$('.widget-menu').fadeIn('slow'); // fade in will now use flex instead of block

Updated fiddle

更新

抱歉,您只是想让 fadeIn 与 flex 一起使用。如果您希望在完成淡入后悬停工作,则需要在下次悬停时从菜单中删除样式

var menu = $('.widget-menu');
menu.css('display', 'flex').hide();
$('body > button').click(function() {
  menu.fadeIn('slow');
});

$('.widget').on('mouseover', function() {
  $(this).find('.widget-menu').hide();
})

New Fiddle

【讨论】:

  • 只是我还是这不起作用?它的结果与我的 jsfiddle 相同。我在火狐上。
  • @JakeM 对不起,误解了你的问题。查看更新
【解决方案2】:

这是因为 jQuery 的 .fadeIn() 方法添加了一个覆盖悬停的内联样式。我已经用一些解释更新了你的代码,以完全按照你的意愿去做:

// When document is ready...
$(document).ready(function() {
    // Fade in the menu, to show the user it's there.
    $('.widget-menu').fadeIn('slow', function() {
        // Fade out the menu, like you want
        $('.widget-menu').fadeOut('slow', function() {
            // Reset the inline style to not mess with the :hover
            $('.widget-menu').attr('style', '');
        });
    }); 
});

【讨论】:

    【解决方案3】:

    问题是 JQuery 在加载 CSS 之后运行,因此 JQuery 接触的任何属性现在都将被覆盖。与其应用更改直接显示菜单,不如尝试使用 JQuery 切换一个模仿 :hover 伪类的类,例如 .hover,然后将该类添加到您的 html 中。一旦鼠标进入然后离开该区域,然后使用 JQuery 删除 .hover 类。这样,JQuery 不会触及您的初始 CSS,并且一旦删除 .hoverclass,它将按预期工作。

    这是一个小提琴演示:https://jsfiddle.net/2dbr2bs3/

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 2013-04-08
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多