我想要实现的结果:继续单击鼠标,然后会根据每次单击的坐标弹出一堆小小的“心脏”图像。换句话说,一键单击将在鼠标坐标上弹出一幅图像。
然后1秒钟后,图像开始消失。较早出现的图像也将较早消失。
我的问题是:除非删除clearInterval
代码,否则图像不会适当消失。这是代码:
// when click, an image pop up
// use addEventListener to do so
// let timer = 0;
let imgList = [];
document.addEventListener("click",function(event){
let img = document.createElement("img");
img.style.position = "absolute";
img.style.left = (event.clientX - 32) + "px";
img.style.top = (event.clientY - 32) + "px";
img.src = "https://placehold.it/64x64.png";
document.body.appendChild(img);
imgList.push({
img:img,
opacity:1,
scale:1,
frame:0
});
});
var timer = setInterval(draw, 1000);
function draw(){
if (imgList.length < 1) {
clearInterval(timer);
timer = null;
}
else {
imgList[0].img.remove();
imgList.splice(0, 1);
}
}
答案 0 :(得分:1)
问题是您在没有图像的情况下取消了间隔计时器,因此,如果用户未在一秒钟内(以及此后一秒钟内,等等)创建图像,计时器将获得已取消,不会再删除其他图像。
我不会为此使用间隔计时器,而是使用专门为添加的图像创建的单个计时器(setTimeout
):
document.addEventListener("click",function(event){
let img= document.createElement("img");
img.style.position="absolute";
img.style.left=(event.clientX-32)+"px";
img.style.top=(event.clientY-32)+"px";
img.src="1.png";
document.body.appendChild(img);
// Remove it after one second
setTimeout(() => {
img.remove();
}, 1000);
});
答案 1 :(得分:0)
您可以将加载事件侦听器添加到添加的图像,并在处理程序中将其超时删除。通用代码段,可能对您的代码有用:
const addImage = (i = 1) => {
let img = document.createElement("img");
img.src = "https://img.icons8.com/metro/2x/like.png";
img.addEventListener("load", () =>
setTimeout(() => document.body.removeChild(img), i*1000));
// ^add load event/timeout here
document.body.appendChild(img);
}
for (let i=0; i < 5; i += 1) {
addImage(i);
}
document.addEventListener("click", () => addImage(1));
<button>Add image</button>
答案 2 :(得分:0)
如果要相隔1秒钟删除图像,则应在“点击”回调中设置timer
。这样,您可以添加尚未设置的时间间隔。
如果要显示每个图像最多1秒,这不是您要寻找的答案。
let imgList = [];
let timer;
document.addEventListener("click",function(event){
let img = document.createElement("img");
img.style.position = "absolute";
img.style.left = (event.clientX - 32) + "px";
img.style.top = (event.clientY - 32) + "px";
img.src = "https://placehold.it/64x64.png";
document.body.appendChild(img);
imgList.push({
img:img,
opacity:1,
scale:1,
frame:0
});
if (!timer) {
timer = setInterval(draw, 1000);
}
});
function draw(){
if (imgList.length < 1) {
clearInterval(timer);
timer = null;
}
else {
imgList[0].img.remove();
imgList.splice(0, 1);
}
}