我一直试图隐藏点击时的图像,以便可以单击标记以显示并隐藏它
我尝试了很多代码,但是对我来说不起作用。 每次单击图像时,图像都会不断添加到页面中
<body>
<a href="#" class="nebulae">nebulae</a>
<div class="col-md-4 first"></div>
<body>
$('.nebulae').click(function(e) {
const img = '<img src="nebulae.jpg" class="rounded float-left">';
$('<img src="nebulae.jpg" class="rounded float-left">').appendTo(".first");
if(img) {
$('html, body').animate({
scrollTop: $(".first").offset().top
}, 1000);
}else{
}
})
我尝试过
if(img) {
$('html, body').animate({
scrollTop: $(".first").offset().top
}, 1000).on( "click", $(this).find( $(this) ));
}else{
$('html, body').animate({
scrollTop: $(".first").offset().top
}, 1000).off( "click", $(this).hide( $(this) ));
}
但也不起作用
答案 0 :(得分:1)
通过单击DOM中的另一个元素来显示或隐藏图像的最简单方法是执行以下操作。试试看。
$(".nebulae").on("click", function () {
$(".first").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="nebulae">nebulae</a>
<div class="col-md-4 first">
<img src="https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png" />
</div>
答案 1 :(得分:0)
我会建议您,不要一次又一次加载图像。将图片放入HTML的div中,然后单击按钮即可显示/隐藏
<body>
<a href="#" class="nebulae">nebulae</a>
<div class="col-md-4 first">
<img src="nebulae.jpg" class="rounded float-left" />
</div>
<body>
$('.nebulae').click(function(e) {
if($(this).hasClass('active')){
$(".first").hide();
$(this).removeClass('active');
}
else{
$(".first").show();
$('html, body').animate({
scrollTop: $(".first").offset().top
}, 1000);
$(this).addClass('active');
}
})
//或者,如果您必须在点击事件后加载图片
<body>
<a href="#" class="nebulae">nebulae</a>
<div class="col-md-4 first">
</div>
<body>
$('.nebulae').click(function(e) {
if($(this).hasClass('active')){
$(".first").html('');
$(this).removeClass('active');
}
else{
$(".first").html('<img src="nebulae.jpg" class="rounded float-left" />');
$('html, body').animate({
scrollTop: $(".first").offset().top
}, 1000);
$(this).addClass('active');
}
})