2013-10-20 115 views
1

我想用javascript動態創建一個隨機數量的框。但是,我怎麼這樣做有點失落。我以爲我會試着在第一次嘗試在html上創建框。所以,這是我的html:試圖創建一個框

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="UTF-8"> 
     <title>Ramdom Boxes</title> 
     <script src="A2Q1.js"></script> 
    </head> 
    <div id="piece8" class="pieces" style="color:#0000ff; top: 50px; left: 50px; width: 60px; height: 60px; cursor: pointer;"></div> 

    <body>  
    </body> 
</html> 

不知何故該方塊沒有顯示出來。但是,當我檢查瀏覽器中的元素時,它似乎在那裏,但沒有顏色。我該如何解決這個問題做一個簡單的2D框顯示

+4

你的div需要身體標記中去。也請張貼A2Q1.js的內容。 – j08691

+0

@ j08691該JavaScript文件是一個總的混亂...這個想法是動態創建隨機數量的隨機顏色,在頁面上隨機位置的框。我原以爲我是這麼做的,但我只是在畫布上繪製對象,而不是將它們存儲在任何地方。這些盒子將隨鼠標事件一起移動。 – user2619395

回答

1

您只需確保所有內容都在<body></body>標記之間。

如果您想要顯示顏色,還需要使用css屬性background-color。顏色改變文字顏色:

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="UTF-8"> 
     <title>Ramdom Boxes</title> 
     <script src="A2Q1.js"></script> 
    </head> 
    <body>  
    <div id="piece8" class="pieces" style="background-color:#0000ff; top: 50px; left: 50px; width: 60px; height: 60px; cursor: pointer;"></div> 
    </body> 
</html> 
1

這可能讓你去:

http://codepen.io/anon/pen/FjrxA

<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="UTF-8"> 
    <title>Random Boxes</title> 
    </head> 
    <body> 
    <script> 
    // Make a loop to create a random amount of boxes 
    var box_count = Math.random() * 100 + 50; 
    for (var i = 0; i < box_count; i++) { 
    // Define an array of css attributes 
    var attr =[ 
     // Assign a colour to the box 
     'background-color:#' + parseInt(Math.random() * 0xFFFFFF, 10).toString(16), 
     // Place the box somewhere inside the window 
     'left:' + Math.random() * window.innerWidth + 'px', 
     'top:' + Math.random() * window.innerHeight + 'px', 
     // Give the box a random size 
     'width:' + Math.random() * 100 + 'px', 
     'height:' + Math.random() * 100 + 'px','position: absolute' 
    ]; 
    // Join the attributes together with semi-colon and write the div to the document 
    // Note: Document write happens at the place where the script is executed 
    document.write('<div style="' + attr.join(';') +'"></div>'); 
    } 
    </script> 
    </body> 
</html> 
+0

屬性數組絕對是一個巨大的幫助,我被困在如何去插入變量。感謝那! – user2619395