You need to either move the <script>
element to the end or wrap your code in a DOM ready or onload handler, because otherwise getElementById()
won't find any elements because they won't have been parsed yet.
Then you need to include a unit (e.g., "px"
) in the left
and top
style properties.
Also there's no need to recalculate the width
and height
for each box since you're doing the same calculation for each. (And you should declare your variables with var
, but although good practice that isn't essential to make it work.)
Here's a working version:
var el=document.getElementById("box1");
var width=window.innerWidth-50;
var height=window.innerHeight-50;
el.style.left=width*Math.random() + "px";
el.style.top=height*Math.random() + "px";
el=document.getElementById("box2");
el.style.right=width*Math.random() + "px";
el.style.top=height*Math.random() + "px";
el=document.getElementById("box3");
el.style.middle=width*Math.random() + "px";
el.style.top=height*Math.random() + "px";
Demo: http://jsfiddle.net/m3Gg3/
Also the left
and top
properties in your CSS should use :
not =
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…