Frage

I wrote some jQuery code to insert buttons in a div and place them randomly across the entire available surface. Unfortunately, no matter how I play with the CSS, they always end up being place in the exact same position, one over the other. This also happens if I put them manually, so it is not a JavaScript/dynamicity issue.

My code is:

<div class="">
    <p><a id="start_button" class="btn btn-primary btn-large">Start game &raquo;</a></p>
</div>
<div id="game_board" class="jumbotron">
   <input type='button' style='left:300px; top:15000px' class='click-point' id='2' value='test' />
</div>

Respectively,

<script>
    $(document).ready(function () {
        var i = 0;
        $('#start_button').click(function () {
            $("#game_board").append($("<input type='button' style='position:absolute; 
                               left:" + Math.random() * ($("#game_board").width()) + " px; 
                               top:" + Math.random() * ($("#game_board").height()) + " px'     
                               class='click-point' id='" + (i++) + "' value='test" + i + "' />"));
        });
    }); 
</script>
War es hilfreich?

Lösung

I made a fiddle here : http://jsfiddle.net/csanonymus/kQAXC/

I used plain JS like this :

var startGame=document.getElementById('start_button');
var min=1;
var max=400;
var board=document.getElementById('game_board');
var i=1;
startGame.onclick=function(){
    var newItem =  document.createElement('input');
    newItem.type="button";
    newItem.style.position="absolute";
    newItem.value="test"+i;
    i++;

    newItem.style.left=Math.floor(Math.random() * (max - min) + min) + "px";
    newItem.style.top=Math.floor(Math.random() * (max - min) + min) + "px";
    board.appendChild(newItem);
}

Andere Tipps

Demo

HTML:

<div>
    <p><a id="start_button" class="btn btn-primary btn-large">Start game &raquo;</a></p>
</div>
<div id="game_board" class="jumbotron"></div>

JS:

var protoBtn = document.createElement("input"),
    board = document.getElementById("game_board"),
    w = board.clientWidth,
    h = board.clientHeight,
    i = 0;
protoBtn.type = 'button';
protoBtn.className = "click-point";
document.getElementById('start_button').onclick = function() {
    var btn = protoBtn.cloneNode(false);
    btn.value = 'test'+ ++i;
    board.appendChild(btn);
    btn.style.left = Math.random() * (w-btn.offsetWidth) + 'px';
    btn.style.top = Math.random() * (h-btn.offsetHeight) + 'px';
};

CSS:

#game_board {
    height: 400px;
    width: 400px;
    border: 1px solid blue;
    position: relative;
}
#game_board > .click-point {
    position: absolute;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top