【问题标题】:Apply :hover on parent div but not on child elements应用 :hover 在父 div 上而不是子元素上
【发布时间】:2021-02-22 04:10:28
【问题描述】:

我想要的是将鼠标悬停在我的 div 上并给它一个框阴影以表明它是可点击的,我有一些内容和一个里面不应该有框阴影的按钮。该按钮在悬停时放大。我设法通过使用pointer-events:none 获得了div 上的box-shadow 并删除了内容上的box-shadow,但我无法从按钮上删除阴影,因为它是可点击的并且不能使用pointer-events:none。是否有任何仅 css 的解决方案,如果没有,还有其他解决方案吗? jsfiddle链接->https://jsfiddle.net/uzq13s47/1/

<!DOCTYPE html>
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>
<link rel="stylesheet" href="./src/styles.css"/>
<body>
    <div id="container">
        <div id="box">
            <p>content</p>
            <h5><button>click me!</button></h5>
        </div>
    </div>
</body>

</html>
body {
  font-family: sans-serif;
}
#box {
  background-color: cyan;
  border-radius: 10px;
  height: 200px;
  width: 200px;
}
p {
  pointer-events: none;
}
#container :hover {
  box-shadow: 0 1px 5px rgb(137, 137, 138);
}
h5 :hover {
  transform: scale(1.2);
  transition-duration: 0.5s;
}

【问题讨论】:

    标签: html css css-selectors pseudo-class


    【解决方案1】:

    您没有按照自己的意愿使用:hover,选择器和伪类(#container :hover)之间的空白意味着所有子元素都将具有悬停效果,在代码中是指(#content *:hover),那就是为什么你有 p 和 button 的悬停效果。

    您可以删除该空白并仅在 #box 和 button 中应用悬停

    另外我建议不要使用标题 h5 作为 button 的父级,因为它在语义方面不太正确

    body {
      font-family: sans-serif;
    }
    
    .button {
      width: 60px;
      height: 60px;
    }
    
    #box {
      background-color: cyan;
      border-radius: 10px;
      height: 200px;
      width: 200px;
    }
    
    #box:hover {
      box-shadow: 0 1px 5px rgb(137, 137, 138);
    }
    
    button:hover {
      transform: scale(1.2);
      transition-duration: 0.5s;
    }
    <div id="container">
      <div id="box">
        <p>content</p>
        <button class="button">click me!</button>
      </div>
    </div>

    【讨论】:

    • 谢谢!它奏效了。我认为空间不会发挥任何作用,而是出于审美原因使用它。
    猜你喜欢
    • 2021-09-23
    • 2010-12-15
    • 2013-11-26
    • 1970-01-01
    • 2019-12-22
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多