首页 > 解决方案 > 使用绝对定位(不重复)在悬停另一个 div 时更改 div 的外观

问题描述

我在具有相对位置(duh)的主 div 顶部有几个绝对位置的 div。当将另一个 div 悬停在同一个父 div 中时,我试图让一个 div 更改其背景颜色等。

现在,我知道相邻 div 类,但它们似乎不起作用(可能是因为绝对定位)。

下面是我的代码示例(实际要大得多)。当悬停在 m2wrap-hover 上(在其他 div 上覆盖 100%)时,更改例如 m2wrap-back 宽度和颜色的最佳方法是什么?

PS 如果不能单独使用 CSS,也可以使用 jQuery 解决方案。

<div class="m2wrap">
  <div class="m2wrap-back">
    <h3 class="m2wrap-back-title">Title</h3>
  </div>
  <h3 class="xhfb-text"> Some text here.. </h3>
  <div class="m2wrap-bz1"></div>
  <div class="m2wrap-bz2"></div>
  <div class="m2wrap-hover"></div>
</div>
<style>
.m2wrap {
    position: relative
}
.m2wrap-back {
    position: absolute;
    top: 15px;
    left: 0;
    width: 110px;
    height: 0;
    text-align: center;
    vertical-align: middle;
}
.m2wrap-hover {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;
    border-radius: 4px;
    opacity: 0.6;
    cursor: pointer;
}
div.m2wrap-hover:hover {
    background-color: #bf0000;
}
</style>

标签: javascriptjqueryhtmlcss

解决方案


你不能用纯 css 和你当前的 html 结构来做到这一点,需要 javascipt 或 jquery 来做到这一点。

例子:

$('.m2wrap-hover').hover(function() {
  $(this).closest('.m2wrap').find('.m2wrap-back').addClass('hover');
}, function() {
  $(this).closest('.m2wrap').find('.m2wrap-back').removeClass('hover');
})
.m2wrap {
    position: relative
}
.m2wrap-back {
    position: absolute;
    top: 15px;
    left: 0;
    width: 110px;
    height: 0;
    text-align: center;
    vertical-align: middle;
}
.m2wrap-hover {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;
    border-radius: 4px;
    opacity: 0.6;
    cursor: pointer;
}
div.m2wrap-hover:hover {
    background-color: #bf0000;
}
.m2wrap-back.hover {
  width: 120px;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m2wrap">
  <div class="m2wrap-back">
    <h3 class="m2wrap-back-title">Title</h3>
  </div>
  <h3 class="xhfb-text"> Some text here.. </h3>
  <div class="m2wrap-bz1"></div>
  <div class="m2wrap-bz2"></div>
  <div class="m2wrap-hover">hover here</div>
</div>

或者,如果您只想使用 css,则需要更改元素的顺序(因为它有position: absolute,所以顺序无关紧要):

.m2wrap {
    position: relative
}
.m2wrap-back {
    position: absolute;
    top: 15px;
    left: 0;
    width: 110px;
    height: 0;
    text-align: center;
    vertical-align: middle;
}
.m2wrap-hover {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;
    border-radius: 4px;
    opacity: 0.6;
    cursor: pointer;
}
div.m2wrap-hover:hover {
    background-color: #bf0000;
}

.m2wrap-hover:hover + .m2wrap-back {
    width: 120px;
    color: red;
}
<div class="m2wrap">
  <h3 class="xhfb-text"> Some text here.. </h3>
  <div class="m2wrap-bz1"></div>
  <div class="m2wrap-bz2"></div>
  <div class="m2wrap-hover">hover here</div>
  <div class="m2wrap-back">
    <h3 class="m2wrap-back-title">Title</h3>
  </div>
</div>


推荐阅读