[英]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.