假设我有以下内容:
<label style="height:50px;width:50px">
<img src="test.svg" width="30" height="30" style="cursor:pointer">
</label>
我的目标是使
在按下时(在移动设备上)做一个可视的弹出。 我所说的弹出,是指快速淡入淡出(例如,通过应用降低的不透明度
,然后还原它)。
为此,我向添加了一个类。 当标签聚焦时,该类影响
不透明度
,如下所示:
null
.pop:focus img{
opacity: 50%;
}
<label class="pop" style="height:50px;width:50px">
<img src="https://www.clipartkey.com/mpngs/m/100-1009872_png-file-svg-laughing-emoji-black-and-white.png" width="30" height="30" style="cursor:pointer">
</label>
null
不用说,这是行不通的。
我需要解决这个问题的最简单的解决方案。 具体地说,我更喜欢纯CSS解决方案(也是这样,如caniuse.com所示,使用支持良好的CSS属性)。 在我看来,像这样的简单任务不应该需要JS或深奥的CSS属性。 当然,除非,我错了,而且这个任务并不简单。
您可以使用复选框来触发如下动画:
HTML:
<label class="pop">
<input type="checkbox" class="trigger">
<img src="https://www.clipartkey.com/mpngs/m/100-1009872_png-file-svg-laughing-emoji-black-and-white.png" width="30" height="30" style="cursor:pointer">
</label>
CSS:
.pop {
display: inline-flex; //to center img
position: relative; //for the checkbox sizing
}
.pop > img {
margin: auto; //center image in the label
opacity: 1; //default opacity
}
.trigger {
position: absolute; //make checkbox the same size as the label
width: 100%;
height: 100%;
top: 0;
left: 0;
opacity: 0; //hide the checkbox so it isn't visible
}
.trigger:checked ~ img {
animation: pop 300ms; //add an animation property to the img sibling when the checkbox is clicked(checked)
}
// pop animation
@keyframes pop {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
JS小提琴
如果你有一点Javascript和CSS动画,这是很容易做到的。 也许是这样的:
null
document.getElementById("img").addEventListener("click", function() {
this.style.animation = "fade 1s linear 1";
setTimeout(function() {
document.getElementById("img").style.animation = "";
}, 1000)
});
@keyframes fade {
0% {
opacity: 1
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
#img {
background-color: red;
border: 1px solid black;
width: 100px;
height: 100px;
}
<label id="label">
<div id = "img"></div>
</label>