简体   繁体   中英

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

I am trying to disappear a moving 2D ball on the click of the mouse. And also I want to do the same on the touch event if it is on the screen touch environment. The problem is that the balls keep moving in the random direction and I want to hide the ball whom I click on.

I used Javascript as I have already mentioned and here is the code which I used to draw ball. function beginDrawCircle(a,b,color){

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

}

I am providing an extra information that I have created three such balls now the click on any one of the ball it should disappear.

Is the ball an IMG, DIV or some other tag? If so, why not add an onclick event handler and set its display to none?

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

Simply use this :

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

As you didn't specify if you were working with jQuery or something like that, a solution in pure Javascript could be:

//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";
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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