简体   繁体   中英

Random div generator with javascript

 <div class="btn-div"> <button class="btn btn-primary">Add div</button> </div> <div class="wrapper"> </div>

I've written a function that creates div in random colors and different locations at the click of a button. But I want each div I created to be deleted when clicked separately. How can I do this? Wrapper is my common div that everything in it

 function RandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } function Top() { return Math.floor((Math.random() * 700) + 200) + "px"; } function Left() { return Math.floor((Math.random() * 300) + 200) + "px"; } function addDiv() { var div = document.createElement("div"); div.className = 'box'; div.style.left = Left(); div.style.top = Top(); div.style.background = RandomColor(); document.querySelector('.wrapper').appendChild(div); } document.querySelector('button').addEventListener('click', addDiv);

Is pretty simple, just add addEventListener with remove after appendChild like:

 function RandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } function Top() { return Math.floor((Math.random() * 700) + 200) + "px"; } function Left() { return Math.floor((Math.random() * 300) + 200) + "px"; } function addDiv() { var div = document.createElement("div"); div.className = 'box'; div.style.left = Left(); div.style.top = Top(); div.style.background = RandomColor(); document.querySelector('.wrapper').appendChild(div); div.addEventListener('click', (e) => { e.target.remove(); }); } document.querySelector('button').addEventListener('click', addDiv);
 div{ width:50px; height:50px; display:inline-block; }
 <div class='wrapper'></div> <button>pressme</button>

Just add this line to your "addDiv" function:


    div.onclick = function(){this.remove();};

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