我正在尝试为图像添加悬停效果以进行放大和缩小。但是立即工作缩小效果,而无需将鼠标指针移到图像上。
.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>
实际上,我想为图像添加悬停效果,当鼠标指针出现在图像上时,它会平滑放大,当鼠标指针移到图像上时,它会缩小。
我了解,您希望在鼠标悬停在卡片上时进行放大,并在鼠标从卡片上移出时立即进行缩小。如果是这种情况,下面的代码片段应该是此问题的修复程序:
.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;
}
.container:hover .image {
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>
问题在于,您在.image
的:hover
上做出了反应,并且由于存在叠加层,一旦叠加层遮盖了图像,css 引擎就会从图像中删除:hover
。将:hover
的目标更改为.container
可确保即使叠加遮挡了图像,它也会存在。
当叠加层到达指针时,它会缩小。当叠加层到达指针时,实际上是叠加层获得悬停效果,而不再是图像。
您可以通过向.container:hover .overlay
css 添加.pointer-events: none
来避免这种情况,如下所示:
.container:hover .overlay {
height: 100%;
pointer-events: none;
}