【问题标题】:How can I implement JS so that when I hover an image in a gallery it affects every other image except the hovered image?如何实现 JS,以便当我将图像悬停在图库中时,它会影响除悬停图像之外的所有其他图像?
【发布时间】:2022-01-13 19:59:09
【问题描述】:

我正在创建一个图像缩略图库,其中每个缩略图都将链接到另一个页面上的全尺寸图像。到目前为止,当用户将鼠标悬停在图像上时,一个红色框会使用 CSS ::before 伪类覆盖图像。

.overlay {
  position: relative;
  display: inline-block;
}

.overlay>img {
  vertical-align: middle;
}

.overlay::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: red;
  transition: 0.2s ease;
  opacity: 0;
}

.overlay:hover::before {
  opacity: 1;
}
<div class="overlay"><img src="https://via.placeholder.com/280x280"></div>
<div class="overlay"><img src="https://via.placeholder.com/333x111"></div>
<div class="overlay"><img src="https://via.placeholder.com/111x333"></div>
<div class="overlay"><img src="https://via.placeholder.com/222x222"></div>
<div class="overlay"><img src="https://via.placeholder.com/111x172"></div>

我想更改交互,以便当用户将鼠标悬停在图像上时,除了悬停在图像上的图像之外,图库中的所有其他图像(具有“覆盖”类)都将被红色框覆盖。这将通过用红色覆盖其他图像来将焦点放在悬停的图像上。

似乎 Javascript 将是完成这项工作的最佳方式,我如何用我已经编写的内容实现 js?

我也在尝试 CSS :not pseudo,但无法使其正常工作。

【问题讨论】:

  • 您可以使用 ~ 在悬停后的叠加元素上产生效果。但是没有办法使用纯CSS来选择之前的那些
  • 您是否编写了任何可以向我们展示的 Javascript。例如鼠标悬停事件。
  • 如果您想在没有 javascript 的情况下创建焦点,请使用背景(例如模糊)。

标签: javascript html jquery css


【解决方案1】:

$('.overlay').hover(fnOver, fnOut)
  function fnOver() {
      $('.overlay').not(this).addClass('active')
  }
  function fnOut() {
      $('.overlay').not(this).removeClass('active')
  }
 .overlay {
    position: relative;
    display: inline-block;
}

.overlay>img {
    vertical-align: middle;
}

.overlay::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: red;
    transition: 0.5s ease;
    opacity: 0;
}

.active::before {
    opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="overlay"><img src="https://via.placeholder.com/280x280"></div>
<div class="overlay"><img src="https://via.placeholder.com/333x111"></div>
<div class="overlay"><img src="https://via.placeholder.com/111x333"></div>
<div class="overlay"><img src="https://via.placeholder.com/222x222"></div>
<div class="overlay"><img src="https://via.placeholder.com/111x172"></div>

【讨论】:

  • 这很好用,谢谢!我以前没有听说过在jquery中遍历。轻松过渡不再有效,但这对我来说不是一个交易破坏者。
  • 我更新了我的答案,轻松过渡正在工作。你可以再试一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多