我有一张图片。当我单击图像时,它会更改边框和不透明度。这是工作。但是如何在单击后在此图像上添加图标?
我的 fiddle :https://jsfiddle.net/ptud8knL/1/
我试图使图标相对定位,然后更改 z-index,但这并不像我想的那样有效。
$('img').on('click', function() {
if ($(this).css('opacity') == 1) {
$(this).css({
'opacity': '0.5',
'border': '3px solid #5cb85c'
});
} else {
$(this).css({
'opacity': '1',
'border': ''
});
}
});
.active {
opacity: 1;
border: 0px solid #5cb85c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://use.fontawesome.com/82851ba7fe.js"></script>
<img id="eiffel" src="https://demo.cloudimg.io/width/200/s/http://sample.li/eiffel.jpg" alt="eiffel">
<i class="fa fa-check-circle fa-5x" aria-hidden="true" style="color:#5cb85c"></i>
最佳答案
最简单的方法是将 img
和 i
放在包含 div
中。然后,您可以将点击处理程序附加到该 div
,并在其上切换一个类。然后,您可以根据该类编写 CSS 规则来隐藏/显示图标,并在 img
上设置样式。试试这个:
$('.container').on('click', function() {
$(this).toggleClass('active');
});
.container {
position: relative;
}
.container i {
display: none;
position: absolute;
top: 135px;
left: 65px;
color: #5cb85c;
}
.container.active img {
border: 3px solid #5cb85c;
opacity: 0.5;
}
.container.active i {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://use.fontawesome.com/82851ba7fe.js"></script>
<div class="container">
<img id="eiffel" src="https://demo.cloudimg.io/width/200/s/http://sample.li/eiffel.jpg" alt="eiffel">
<i class="fa fa-check-circle fa-5x" aria-hidden="true"></i>
</div>
关于jquery - 单击jquery和css后如何在图像上添加图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45036215/