2016-06-23 3 views
0

div를 만들고 2 초마다 화면의 임의의 위치에 배치하려고합니다. PHP 또는 Javascript를 사용하여이 작업을 어떻게 수행합니까? 나는 CSS와 같은 것들을 사용하는 것이 좋습니다. 사업부 :무작위로 div 생성

var blueMass = document.createElement('div'); 
blueMass.style.position = "absolute"; 
blueMass.innerHTML = "<img src='./pic/bluemass.png' height='35' width='35' />"; 
blueMass.id = "bluemass"; 
blueMass.className = "bluemass"; 

// my timer 
window.setInterval(function(){ 
    // Create the divs in here 
}, 3000); 
<div class="bluemass" id="bluemass"> 
    <img src='./pic/bluemass.png' height='35' width='35' /> 
</div> 
+1

당신은 그냥 무작위 X를 얻을 타이머를 만들 것와 y는 각각의 반복 좌표. PHP가 아니라 자바 스크립트를 사용해야합니다. –

+1

나는 PHP를 사용하는 이유가 보이지 않거나 PHP가 이것을 수행 할 수 있다고 생각하지 않는다. – j08691

+0

@DanWeber 나는 타이머를 가지고 있지만 편집 할 것이다. 그러나 div를 만드는 데 문제가있다. 웹 개발로) – Symbios

답변

0

그냥 폭 얻고 문서의 높이와 난수를 생성하는 것을 사용한다. 이미 html로 요소를 만들었으므로 JS의 모든 요소를 ​​다시 실행할 필요가 없습니다.

사양에서 2 초마다를 원하므로 타이머에서 2000 밀리 초가됩니다.

타이머 기능에서 요소의 왼쪽과 맨 위에 새로운 난수를 추가하기 만하면됩니다.

var blueMassElement = document.getElementById('bluemass'); 
 
var currentTop = 0; 
 
var documentHeight = document.documentElement.clientHeight; 
 
var documentWidth = document.documentElement.clientWidth; 
 

 
window.setInterval(function() { 
 
    // Create the divs in here 
 
    
 
    currentTop = Math.floor(Math.random() * documentHeight) + 1; 
 
    currentLeft = Math.floor(Math.random() * documentWidth) + 1; 
 
    
 
    blueMassElement.style.top = currentTop + "px"; 
 
    blueMassElement.style.left = currentLeft + "px"; 
 
}, 2000);
#bluemass { 
 
    position:absolute; 
 
}
<div id="bluemass" class="bluemass"> 
 
    <img height="35" width="35" src='http://vignette4.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437' /> 
 
    </div>

2

// no jQuery 
 
$=document.querySelector.bind(document); // create selector 
 
setInterval(function(){ 
 
    s=$('div').style; 
 
    s.top=Math.random()*window.innerWidth+'px'; // multiply random (0..1) value by window height (you may want to subtract div height) 
 
    s.left=Math.random()*window.innerHeight+'px'; // ... height ... 
 
},2000)
div{position:fixed}
<div>div</div>

// with jQuery 
 
setInterval(function() { 
 
    $('#mydiv').css({ 
 
    top: Math.random() * ($(window).height() - $('#mydiv').height()) + 'px', // multiply random .width(0..1) value by window height minus div height 
 
    left: Math.random() * ($(window).width() - $('#mydiv').width()) + 'px' 
 
    }) 
 
}, 2000)
#mydiv{position:fixed}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="mydiv">div</div>

+0

첫 번째 줄 대신 jQuery를 사용할 수 있습니다 – Dimava

+1

왜 OP가이 문제를 해결해야합니까? *** 좋은 대답 ***은 무엇을했는지에 대한 설명과 왜 그런 방식으로했는지에 대한 설명을 OP에서뿐만 아니라 미래의 방문객에게도 제공합니다. –

관련 문제