如何在点击时淡出图像



我最近开始学习编程,我非常喜欢它。话虽如此,我还是个新手,而且非常……新手。我想知道是否有一种方法可以让我的居中图标淡出,而不是在点击时消失。我创建的叠加也是一样。

function functionHide(divId, divId2, ) {
let x = document.getElementById(divId);
let y = document.getElementById(divId2);
x.style.display = "none";
y.style.display = "block";
}
#icon {
content: url('https://i.picsum.photos/id/178/536/354.jpg?hmac=ehK1NKjWRA3SRY3R4dCo7ejDyrzqqjDWwtwo2TYLpHk');
height: 256px;
width: 256px;
top: 50%;
left: 50%;
position: fixed;
margin-top: -128px;
margin-left: -128px;
z-index: 1;
transition: .4s ease;
display: block;
}
#overlay {
background-color: rgba(0, 0, 0, 0.5);
width: 100%;
height: 100%;
display: none;
}
#icon:hover {
cursor: pointer;
transform: scale(1.5);
transition: transform .4s;
}
<div id="icon" onclick="functionHide('icon', 'overlay')"></div>
<div id="background">
<div id="overlay"></div>
</div>

有一个很好的淡出的例子。

在隐藏类中使用动画,例如:

.hide {
animation-name: fadeOut;
animation-duration: 3s;
}
@keyframes fadeOut {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}

请记住使用-webkit-moz等浏览器扩展。

使用@keyframes动画或更改图像的不透明度,假定设置了transition

@keyframes

function functionHide(divId, divId2, ) {
let x = document.getElementById(divId);
let y = document.getElementById(divId2);
x.style.animation = "fadeOut 0.2s forwards";
y.style.animation = "fadeOut 0.2s forwards";
}
#icon {
content: url('https://i.picsum.photos/id/178/536/354.jpg?hmac=ehK1NKjWRA3SRY3R4dCo7ejDyrzqqjDWwtwo2TYLpHk');
height: 256px;
width: 256px;
top: 50%;
left: 50%;
position: fixed;
margin-top: -128px;
margin-left: -128px;
z-index: 1;
transition: .4s ease;
display: block;
}
#overlay {
background-color: rgba(0, 0, 0, 0.5);
width: 100%;
height: 100%;
display: none;
}
#icon:hover {
cursor: pointer;
transform: scale(1.5);
transition: transform .4s;
}
@keyframes fadeOut{
from{
opacity:1;
}
to{
opacity:0;
}
}
<div id="icon" onclick="functionHide('icon', 'overlay')"></div>
<div id="background">
<div id="overlay"></div>
</div>

解释
fadeOut 0.2s forwards
^       ^    ^
name of animation
duration of animation
instructs the animation to run once, then stay in the same state after animation

或者你可以考虑像这样使用jQuery的fadeOut()函数:

function functionHide(divId, divId2, ) {
let x = document.getElementById(divId);
let y = document.getElementById(divId2);
$(x).fadeOut();
$(y).fadeOut();
}
#icon {
content: url('https://i.picsum.photos/id/178/536/354.jpg?hmac=ehK1NKjWRA3SRY3R4dCo7ejDyrzqqjDWwtwo2TYLpHk');
height: 256px;
width: 256px;
top: 50%;
left: 50%;
position: fixed;
margin-top: -128px;
margin-left: -128px;
z-index: 1;
transition: .4s ease;
display: block;
}
#overlay {
background-color: rgba(0, 0, 0, 0.5);
width: 100%;
height: 100%;
display: none;
}
#icon:hover {
cursor: pointer;
transform: scale(1.5);
transition: transform .4s;
}
@keyframes fadeOut{
from{
opacity:1;
}
to{
opacity:0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="icon" onclick="functionHide('icon', 'overlay')"></div>
<div id="background">
<div id="overlay"></div>
</div>

最新更新