2014-03-02 3 views
0

상자 안에 임의의 위치에 X를 배치 할 값을 생성 할 수 없습니다. 어떤 생각이 잘못 됐습니까?Math.random not working

var putAnXBtn = document.getElementById("putAnXButton"); 
putAnXBtn.onclick = function(){ 

     var theBox = document.getElementById("putAnX"); 

     // width and height of the box 
     var width = theBox.clientWidth; 
     var height = theBox.clientHeight; 


     var yPosition = Math.random()* width; // Not able to generate a value between 0 and the height 
     var xPosition = Math.random()* height; //Not able to generate a value between 0 and the width 


     var theXElement = document.getElementById("theX"); 
     theXElement.innerHTML="X"; 
     theXElement.style.top = parseInt(yPosition)+'px'; 
     theXElement.style.left = parseInt(xPosition)+'px'; 

} 
+0

당신은뿐만 아니라 당신의 HTML을 보여 주실 래요? –

+1

'width'와'height' 검사가 예상대로입니다 –

+0

'theX'에는 위치 설정이 없으므로 위쪽과 왼쪽 값을 설정해도 이동하지 않습니다. CSS에서'theX'에 대한 상대적인 위치를 설정하면됩니다. – adeneo

답변

0

나는

Math.floor(Math.Random() * width) 
Math.floor(Math.Random() * height) 

를 사용하는 것이 좋습니다 플러스 당신은 임의의 위치를 ​​생성하는 동안 heightwidth 반전이있다.

변경이이에

var yPosition = Math.random() * width; 
var xPosition = Math.random() * height; 

은 :

var yPosition = Math.floor(Math.random() * height); 
var xPosition = Math.floor(Math.random() * width); 

그렇지 않으면 X는 컨테이너 경계의 외부에서 생성 될 수있다.

뿐인http://jsfiddle.net/9t46F/

+0

고마워요.하지만 차이점을 볼 수는 없습니다. Math.floor 또는 Math.random을 사용할 때. 바이올린은 두 가지 방식으로 똑같이 행동합니다. 나는 여기 새로 왔어. 그래서 내가 뭘 알아? – user3369726

+0

Math.floor()가하는 일을 이해하려면 [here] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor)를 참조하십시오. [here] (http://jsfiddle.net/VdZe3/) 다른 결과를 보여주는 예 – BeNdErR

+0

좋아, 나는 이해한다고 생각하지만, 왜 Fiddle은 같은 방식으로 다른 행동을하고 있는가? – user3369726