如何使用onclick事件创建多个框

时间:2012-06-06 10:19:42

标签: javascript

onclick后,我需要生成具有唯一ID和随机位置的多个框。

这是我的effort so far

<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的解决方案。

1 个答案:

答案 0 :(得分:0)

要生成,您需要使用div“scene”或您想要使用的任何其他空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.
}

另外,不要忘记功能参数 - 并且您需要阅读可见框的注释