: 将鼠标悬停在具有边框半径的 div 上

:hover on a div with a border radius

我在悬停和带有边框半径的 div 方面遇到问题。

当 div 内部有图像和边框半径时,它的 "hitbox" 是不正确的。将鼠标悬停在 div 的任何角上(如果它没有边框半径,角将位于何处)会导致显示悬停样式。我希望样式仅在鼠标实际位于圆圈内时显示。

如果div里面什么都没有,那么div的"hitbox"是正确的,但是当里面有元素的时候就越界了。

我可以在 div 中添加背景图片,但出于可访问性原因,我不想这样做。

#test-wrapper {
  background-color: #EEE;
  border: 4px dashed #999;
  display: inline-block;
}

#switcher {
  border-radius: 50%;
  overflow: hidden;
  position: relative;
}

#switcher,
#switcher .first,
#switcher .second {
  width: 100px;
  height: 100px;
}

#switcher .first,
#switcher .second {
  position: absolute;
  top: 0;
  left: 0;
}

#switcher:hover .first {
  display: none;
}
  <!-- This is used to show the "hitbox" for the switcher and has no effect on the switcher itself -->
<div id="test-wrapper">
  <div id="switcher">
    <!-- Shown on hover -->
    <img src="https://placeholdit.imgix.net/~text?txtsize=30&txt=Second&w=100&h=100&txttrack=0" class="second">
    
    <!-- Always shown -->
    <img src="https://placeholdit.imgix.net/~text?txtsize=30&txt=First&w=100&h=100&txttrack=0" class="first">
  </div>
</div>

这里的问题是子元素不继承其父元素的border-radius。有两种方法可以实现您想要的:您可以将子元素的 border-radius 设置为匹配或大于父元素的半径,或者设置 overflow 属性父元素的 hidden.

这是一个说明问题和两种解决方案的快速片段:

*{box-sizing:border-box;color:#fff;font-family:arial;margin:0;padding:0;}
div{
    background:#000;
    border-radius:50%;
    display:inline-block;
    line-height:150px;
    margin:10px;
    text-align:center;
    vertical-align:top;
    width:150px;
}
p{
    background:rgba(255,0,0,.25);
}
div:nth-of-type(2)>p{
    border-radius:50%;
}
div:nth-of-type(3){
    overflow:hidden;
}
<div><p>Square hit area</p></div><div><p>Round hit area 1</p></div><div><p>Round hit area 2</p></div>


如果子元素是图像,那么您需要使用图像贴图来裁剪它们的命中区域(图片来源:Border-radius and :hover state area issue),如下所示:

*{box-sizing:border-box;color:#fff;font-family:arial;margin:0;padding:0;}
div{
    background:#000;
    border-radius:50%;
    display:inline-block;
    margin:10px;
    text-align:center;
    vertical-align:top;
    width:calc(33% - 20px);
    max-width:600px;
}
img{
    display:block;
    cursor:pointer;
    height:auto;
    width:100%;
}
div:nth-of-type(2)>img{
    border-radius:50%;
}
div:nth-of-type(3){
    overflow:hidden;
}
<div><img alt="" height="600" src="http://lorempixel.com/600/600/nature/3/" width="600"></div><div><img alt="" height="600" src="http://lorempixel.com/600/600/nature/3/" width="600" usemap="circle"></div><div><img alt="" height="600" src="http://lorempixel.com/600/600/nature/3/" width="600" usemap="circle"></div>
<map name="circle"><area shape="circle" coords="0,100%,100%,100%"></map>

我似乎找到了解决方法,如果父元素隐藏了 overflow 而您只是将图像 z-index 设置为 -1 或低于父元素的其他元素,它也可以工作。 虽然不知道为什么