javascript - 使用javascript连续移动div位置

标签 javascript html css

我想从左到右然后从上到下连续移动我的 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);

我不明白我现在能做什么?

最佳答案

函数持续运行,但是因为 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 的当前左侧和顶部值。

这是更新后的 fiddle :https://jsfiddle.net/LLqmL33p/2/ 抱歉我的英语不好。

关于javascript - 使用javascript连续移动div位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36277323/

相关文章:

javascript - 如何在 Bootstrap 的导航中设置预先输入的样式?

javascript - 来自 csv 数据的 X 轴时间刻度

javascript - 我的 JQuery 图像幻灯片似乎不起作用

javascript 无法在 struts html 标签上工作

css - 如何配置 simple_form 以显示验证状态

css - 如何保持img :hover within the page boundaries?

javascript - jQuery Page 在单页中按下按键时每次向下滚动

javascript - 第二次单击按钮时执行的 Angularjs ng-click 函数

javascript - 在laravel中使用ajax提交多个表单

javascript - 使用什么来创建在 apache2 上运行的蜂鸣器 Web 应用程序