2013-10-20 116 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