繁体   English   中英

在javascript中鼠标单击该对象时消失对象。 在我的情况下,我想通过点击鼠标来消失一个弹跳球

[英]Disappear object on mouse click on that object in javascript. In my case I want to disappear a bouncing ball on the click of the mouse

我试图通过单击鼠标使移动的 2D 球消失。 如果它在屏幕触摸环境中,我也想对触摸事件做同样的事情。 问题是球一直在随机方向移动,我想隐藏我点击的球。

正如我已经提到的,我使用了 Javascript,这里是我用来绘制球的代码。 函数 beginDrawCircle(a,b,color){

ctx.beginPath();
ctx.arc(a, b, ballRadius, 0, Math.PI*2);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath(); 

}

我提供了一个额外的信息,我已经创建了三个这样的球,现在点击任何一个球它应该消失。

球是 IMG、DIV 还是其他标签? 如果是这样,为什么不添加一个 onclick 事件处理程序并将其显示设置为无?

<img src="ball.png" id="ball" onclick="this.style.display='none'"/>

只需使用这个:

document.getElementById("ball").onclick = foo;
foo(){
this.style.display = 'none';
}

由于您没有指定是否使用 jQuery 或类似的东西,纯 Javascript 中的解决方案可能是:

//Assuming all the balls are of class ".ball"
var balls = document.querySelectorAll(".ball");
Array.prototype.forEach.call(balls, function(ball){
    ball.addEventListener("click", function(event){
        ball.style.display = "none";
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM