【问题标题】:Hiding and showing elements with jQuery flickers in Chrome and Edge在 Chrome 和 Edge 中使用 jQuery 闪烁隐藏和显示元素
【发布时间】:2017-04-07 12:35:24
【问题描述】:

我正在尝试使用 jQuery 制作一个简单的动画,该动画在 Firefox 中运行良好,但在 Chrome 和 Edge 中闪烁,这是jsfiddle,这是代码:

HTML

<div id="boxes-wrapper">
  <div class="box"></div><div class="box"></div><div class="box"></div>
</div>

CSS

.box {
  width: 150px;
  height: 150px;
  display: inline-block;
  margin: 0;
  padding: 0;
  vertical-align: top;
}

.box:first-child {
  background: pink;
}

.box:nth-child(2) {
  background: skyblue;
}

.box:nth-child(3) {
  background: gold;
}

.box.hover {
  position: relative;
  z-index: 20;
}

html, body {
  position: relative;
  width: 100%;
  height: 100%;
}

#shadow {
  display: none;
  position: absolute;
  left: 0;
  top: 0;
  background: black;
  opacity: 0.7;
  z-index: 10;
  width: 100%;
  height: 100%;
}

JavaScript

$('.box').hover(function() {
    $(this).addClass('hover');
  $('#shadow').show();
}, function() {
    $(this).removeClass('hover');
  $('#shadow').hide();
});

我已经挖掘了一些关于 SO 的问题,但没有一个回答如何消除闪烁。

【问题讨论】:

  • 为什么不为你的影子做一个单独的悬停,让它显示在盒子包装悬停上
  • 因为我需要知道哪个孩子触发了悬停,这样我才能向它添加一个类
  • 实际上已经查看了您的代码,无法像隐藏叠加层一样做您想做的事情(这是导致闪烁的原因),无法悬停另一个框并且非悬停的框在覆盖层后面
  • 试了也没用
  • 废掉最后一条评论,我有一个混合了 CSS 的解决方案,它可以工作 - 有点小技巧,但可能是你所希望的最好的解决方案

标签: javascript jquery css google-chrome animation


【解决方案1】:

好的,问题是您的叠加层覆盖了未悬停的框,因此当前需要消失才能悬停其他框。

闪烁是由你的框之间的空间引起的 - 一旦鼠标离开,覆盖就被隐藏了。

为了解决这个问题,您需要混合 css 并将覆盖层的悬停移动到包装盒(代码中的 cmets):

// remove overlay from this:
$('.box').hover(function() {
  $(this).addClass('hover');
}, function() {
  $(this).removeClass('hover');
});

// add this:
$('#boxes-wrapper').hover(function() {
  $('#shadow').show();
}, function() {
  $('#shadow').hide();
});
html,
body {
  position: relative;
  width: 100%;
  height: 100%;
}
#boxes-wrapper {
  float: left;
  /*this makes the wrapper the same width as the boxes, you may need to add a clear fix after this*/
}
.box {
  width: 150px;
  height: 150px;
  display: inline-block;
  margin: 0;
  padding: 0;
  vertical-align: top;
}
.box:first-child {
  background: pink;
}
.box:nth-child(2) {
  background: skyblue;
}
.box:nth-child(3) {
  background: gold;
}
.box.hover {
  position: relative;
  z-index: 20;
}
#shadow {
  display: none;
  position: absolute;
  left: 0;
  top: 0;
  background: black;
  opacity: 0.7;
  z-index: 10;
  width: 100%;
  height: 100%;
  /* add the following - means that the mouse hover will "go through" the overlay */
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boxes-wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

<div id="shadow"></div>

【讨论】:

  • 太棒了,但是当我将它应用到我的项目中时它仍然无法工作:(
  • 你能用你更新的代码创建一个小提琴来复制这个问题吗:jsfiddle.net
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多