2016-02-15 34 views

回答

0

Math.floor((Math.random() * 10) + 1)會給隨機數1到10

使用.createElement()和絕對位置之間:

var img = document.createElement('myImage'); 
myImage.src = 'pic.jpg'; 
myImage.style.top = Math.floor((Math.random() * 10) + 1) + 'px'; 
myImage.style.left = Math.floor((Math.random() * 10) + 1) + 'px'; 

使用圖像元素構造和保證金:

var myImage = new Image(); 
myImage.src = 'pic.jpg'; 
myImage.style.marginTop = Math.floor((Math.random() * 10) + 1) + 'px'; 
myImage.style.marginLeft = Math.floor((Math.random() * 10) + 1) + 'px'; 

https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

+0

.....這是行不通的....連續生成的圖像不是隨機@Vinny Mannello –

+0

@ManavJain你就需要使用marginTop和marginLeft與你提到的代碼。 https://jsfiddle.net/sgrcm0z3/ –

+0

https://jsfiddle.net/mjmanav4/qtnLax6m/1/ –

0
function createImage(){ 
var img = document.createElement('img'); 
    img.src = 'yourImage.png'; 
    img.style.top = '10px'; 
    img.style.left = '10px'; 
    document.body.appendChild(img) 
} 

而不是10你現在可以將它設置爲一個隨機數。

相關問題