2016-03-29 49 views
4

我想将我的div位置连续从左到右移动,然后从上到下移动。使用javascript连续移动div位置

第一次移动我的代码后停止。

https://jsfiddle.net/LLqmL33p/

 function placeDiv(x_pos) { 
    var d = document.getElementById('boxed'); 
    d.style.position = "absolute"; 
    d.style.left = x_pos+'px'; 
    setTimeout(function(){ placeDiv2(10); }, 1000); 

} 
function placeDiv2(y_pos) { 
    var d = document.getElementById('boxed'); 
    d.style.position = "absolute"; 
    d.style.top = y_pos+'px'; 
    setTimeout(function(){ placeDiv(15); }, 1000); 

} 

placeDiv(10); 

我不能明白现在该怎么做?

+0

_是,_这段代码将继续运行..使用'setTimeout'添加一些延迟执行.. – Rayon

+0

请检查https://jsfiddle.net/LLqmL33p/ @RayonDabre – Beffing

回答

7

的功能保持连续运行,但由于X_POS = 10,Y_POS = 15具有相同的值总是那么div会不动,试试这个:

function placeDiv(x_pos) { 
    var d = document.getElementById('boxed'); 
    d.style.position = "absolute"; 
    if(d.style.left=="") 
    { 
     var cur_left=0; 
    } 
    else 
    { 
     var cur_left=parseFloat(d.style.left); 
    } 
    d.style.left = (cur_left+x_pos)+'px'; 
    setTimeout(function(){ placeDiv2(10); }, 1000); 

} 
function placeDiv2(y_pos) { 
    var d = document.getElementById('boxed'); 
    //d.style.position = "absolute"; 
    if(d.style.top=="") 
    { 
     var cur_top=0; 
    } 
    else 
    { 
     var cur_top=parseFloat(d.style.top); 
    } 
    d.style.top = (cur_top+y_pos)+'px'; 
    setTimeout(function(){ placeDiv(15); }, 1000); 

} 

placeDiv(10); 

我做的是我x_pos上和Y_POS值与当前左边和DIV的顶部值。

这里是更新的小提琴:https://jsfiddle.net/LLqmL33p/2/ 对不起,我的英语不好。

0

@keyframes move { 0%{ left: 0px; top: 0px; } 100%{ left: 100%; top: 100%; }} 
 

 

 
div { 
 
    width: 100px; 
 
    height: 100px; 
 
    background: red; 
 
    position: absolute; 
 
    animation: move 10s linear infinite; 
 
}
<div></div>

+0

我只需要JavaScript。你可以查看https://jsfiddle.net/LLqmL33p/ @Bob – Beffing

0

的setTimeout是为了执行一次,在指定延迟后。

它会显示你想使用setInterval

0

https://jsfiddle.net/LLqmL33p/1/

 ////css 
    @keyframes move { 0%{ left: 0px; top: 0px; } 50%{ left: 80%; top: 80%; } 80%{left: 90%; top: 10%;} 100%{left: 0%; top: 0%;}} 


div { 
    width: 100px; 
    height: 100px; 
    background: red; 
    position: absolute; 
    animation: move 10s linear infinite; 
} 

     /////html 
     <div></div> 
+0

试试这个不断移动 –