首页 > 解决方案 > 悬停放大和缩小背景无法正常工作

问题描述

我正在尝试为图像添加悬停效果以进行放大和缩小。但无需在图像上移动鼠标指针即可立即产生缩小效果。

.container {
  overflow: hidden;
  position: relative;
  width: 50%;
}

.image {
  display: block;
  width: 100%;
  height: auto;
  background-size: cover;
  background-position: center;
  transition: all 0.5s ease;
}

.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: black;
  overflow: hidden;
  width: 100%;
  height: 0;
  transition: .5s ease;
  opacity: 0.5;
}

.container:hover .overlay {
  height: 100%;
}

.text {
  color: white;
  font-size: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  text-align: center;
}

.image:hover {
  transform: scale(1.5);
  transition: .5s ease;
}
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <h2>Slide in Overlay from the Bottom</h2>
  <p>Hover over the image to see the effect.</p>
  <div class="container">
    <img src="https://www.activeconnections.org/wp-content/uploads/avatar-1.png" alt="Avatar" class="image">
    <div class="overlay">
      <div class="text">Hello World</div>
    </div>
  </div>
</body>

</html>

实际上我想为图像添加悬停效果,当鼠标指针落在图像上时,它会平滑放大,当鼠标指针移到图像上时,它会缩小。

标签: htmlcss

解决方案


当覆盖到达您的指针时,它会缩小。当叠加层到达您的指针时,它实际上是获得悬停效果的叠加层,而不是图像。

您可以通过添加.pointer-events: none到您的.container:hover .overlaycss 来避免这种情况,如下所示:

.container:hover .overlay {
  height: 100%;
  pointer-events: none;
}

推荐阅读