2014-03-04 41 views
0

我編寫了一些jQuery代碼在div中插入按鈕,並將它們隨機放置在整個可用表面上。不幸的是,無論我如何使用CSS,他們總是最終處於完全相同的位置,一個在另一個之上。 這也發生,如果我手動把它們,所以它不是一個JavaScript /動態問題。無法將輸入按鈕放入div

我的代碼是:

<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> 

分別,

<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> 
+1

嘗試使遊戲板和兩個按鈕'位置:絕對'。並確保董事會有一個確定的寬度和高度。 –

+0

如果你想從一個元素的位置首先設置它的位置爲絕對 – csanonymus

+1

並停止將變量放置在引號中...這不是PHP – csanonymus

回答

0

我做了這裏提琴:http://jsfiddle.net/csanonymus/kQAXC/

我用純JS是這樣的:

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); 
} 
0

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; 
}