css中我们经常遇到hover态的样式处理,通常我们用的更多的是控制自身或者控制子元素,但是遇到同层级元素怎么处理呢?

直接上一个很经典的例子,也是在项目中遇到的:

例子是一个图片预览控件,需求:当鼠标移动到可视区域内时显示左右切换按钮和下方的操作区,但是当用户左右切换图片时,我们发现如果按钮操作区一直处于显示状态会遮盖部分图片信息,严重影响用户体验。所以,当鼠标移动到左右切换按钮时,我们需要将按钮操作区隐藏

1、如果a是b的父元素,使用 #a:hover #b{ }

2、如果a和b是同级元素,相邻同级元素使用 #a:hover + #b{ },不相邻使用 #a:hover ~ #b{ }。(不管是否相邻,都可以直接使用~连接符)

上面示例的代码在下方给出:

<!DOCTYPE html>
<html>
  <head>
    <style>
      .container {
        width: 700px;
        height: 400px;
        box-shadow: 0 0 6px #ccc;
        background: rgba(0, 0, 0, 0.1);
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        cursor: pointer;
      }
      .image {
        width: 600px;
        height: 300px;
        background: #ccc;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .left,
      .right {
        display: none;
        position: absolute;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
        width: 40px;
        height: 40px;
        font-size: 15px;
        top: 50%;
        transform: translate(0, -50%);
        background: #aaa;
      }
      .left {
        left: 40px;
      }
      .right {
        right: 40px;
      }
      .opt {
        display: none;
        position: absolute;
        bottom: 60px;
        left: 50%;
        transform: translate(-50%, 0);
        background: #aaa;
        padding: 10px 20px;
      }
      .container:hover .left {
        display: flex;
      }
      .container:hover .right {
        display: flex;
      }
      .container:hover .opt {
        display: flex;
      }
      .left:hover ~ .opt {
        display: none;
      }
      .right:hover + .opt {
        display: none;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="image">图片展示</div>
      <div class="left">←</div>
      <div class="right">→</div>
      <div class="opt">按钮操作区</div>
    </div>
  </body>
</html>

 

更多推荐

hover控制同级元素css样式