按下时将 css 应用于<img>内部<label> <img> (移动)



>想象一下我有以下内容:

<label style="height:50px;width:50px">
<img src="test.svg" width="30" height="30" style="cursor:pointer">
</label>

我的目标是使<img>在按下时(在移动设备上(发出视觉弹出。通过流行,我的意思是快速淡入和淡出(例如,通过应用降低的opacity,然后恢复它(。

为此,我在<label>中添加了一个类。此类会影响标签聚焦时opacity,如下所示:

.pop:focus img{
opacity: 0.5;
}
<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>

不用说,这是行不通的。

我需要最简单的解决方案来解决这个问题。具体来说,我更喜欢纯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动画。也许是这样的:

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>

或者,如果你不想要 Js,你可以做这样的事情:

#img {
width: 100px;
height: 100px;
background-color: red;
transition: 1s;
}
#img:active {
opacity: 0;
}
<label id="label">
<div id = "img"></div>
</label>

如果将文本输入移动到标签之前,则可以在聚焦输入时触发动画,这在单击标签时发生。然后,可以通过例如将flex与行反转一起使用,在标签之后再次显示输入。

<div class="pop-label-image">
<input type="text" id="example">
<label for="example">
<img src="https://via.placeholder.com/30">
</label>
</div>
.pop-label-image {
display: flex;
flex-direction: row-reverse;
align-items: baseline;
justify-content: start;
}
@keyframes pop {
0% {
opacity: 1
}
50% {
opacity: .5;
}
100% {
opacity: 1;
}
}
.pop-label-image input:focus + label {
animation: pop 500ms;
}

最新更新