簡體   English   中英

單擊時刪除圖像

[英]Remove image when clicked

基本上,我正在嘗試創建一個游戲,目標是單擊圖像使其消失。

我做了一個函數,可以在屏幕上的隨機位置生成一張圖像。 然后,我還進行了一個間隔,以使其在隨機位置產生15張圖像。 現在,我希望圖像在單擊時消失。

我的想法是創建一個“單擊”功能,因此如果單擊圖像,則“ img.style.height ='0px';

但是,我沒有得到任何幫助。

在文檔中插入所有圖像之后,為所有圖像定義一個click偵聽器,並在單擊時隱藏圖像。 一個簡單的例子

 function hide(el) { el.style.display = 'none'; } var imgs = document.getElementsByTagName("img"); for(let i = 0; i < imgs.length; i ++) { imgs[i].addEventListener('click', function(e) { hide(e.target); }); } 
 <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgYxw854mGOAp8f16evj_WYw_Ph385nUVygQdxHvuD9b3ueJxT0A" id="1" alt="Mountain View 1"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT8_MiTkMX9nLJ9udtnwOQekIrQwUQ9KMZiU4fLfI7YhXCyIGZn" id="2" alt="Mountain View 2"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgR4KM-zrVRmfdGPf5bll9vq4uLw7FSLpTmHUf9-RkYZ92Ey8Q" id="3" alt="Mountain View 3"> 


您的代碼應該像這樣更改

 function SpawnW() { var img = document.createElement("img"); img.setAttribute("style", "position:absolute;"); img.setAttribute("src", "women3.png"); document.body.appendChild(img); img.setAttribute("onclick", "this.style.display = 'none'"); // pictureNumber++; } SpawnW(); 

希望這對您有所幫助。

采用

<img onclick="this.style.visibility = 'hidden'" src="..." />

如果要保留圖像占用的空間,否則:

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

如果需要從對象數組中刪除圖像,則還需要定義一個函數。

在您的代碼中:

img.setAttribute("onclick", "this.style.visibility = 'hidden'" );

要么

img.setAttribute("onclick", "this.style.display = 'none'" );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM