簡體   English   中英

如何使用onclick事件創建多個框

[英]How to create multiple boxes with onclick event

onclick ,我需要生成多個具有唯一ID和隨機位置的框。

到目前為止,這是我的努力

<h1>The Amazing Box App</h1>
<form id="data">
<ol>
<li>Pick a name for your Amazing Box: <br>
<label for="name">Name: </label>
<input type="text" id="name" size="20" placeholder="My Amazing Box ..">
</li>
<li>Pick a color for your Amazing Box: <br>
<select id="color">
<option value="">Pick a color</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="indigo">Indigo</option>
<option value="violet">Violet</option>
</select>
</li>
<li>How many Amazing Boxes do you want to create?<br>
<input type="radio" id="five" name="amount" value="5">
<label for="five">5</label><br>
<input type="radio" id="ten" name="amount" value="10">
<label for="ten">10</label><br>
<input type="radio" id="fifteen" name="amount" value="15">
<label for="fifteen">15</label><br>
</li>
</ol>
<p>
<input type="button" id="generateButton" value="Generate My Amazing Boxes">
<input type="button" id="clearButton" value="Clear My Amazing Boxes">
</p>
</form>
<div id="scene">
</div>

我正在尋找一個純JavaScript的解決方案。

要生成,您需要使用div“場景”或您要使用的任何其他空div標簽。

功能需要類似於以下內容:

function generateboxes(num, color) {
    clearboxes(); //first clear them
    for (var i=0; i<num; i++) {
        var top = Math.floor(Math.random()*300); //300 is the max vertical offset
        var left = Math.floor(Math.random()*200); //200 is the max horizontal offset
        var boxstyle = "position:absolute; top:"+top+"px; left:"+left+"px; background-color:"+color+";"; //Definition of box styles (you must set width and height for them to be visible)
        document.getElementById('scene').innerHTML += "<div style=\""+boxstyle+"\"></div>"; //Add one more box to the group
    }

function clearboxes() {
    document.getElementById('scene').innerHTML = ""; //By resetting the HTML of the div, we remove the boxes.
}

另外,不要忘記函數參數 - 您需要閱讀可見框的注釋

暫無
暫無

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

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