如何缓慢移动DOM元素

How I can move DOM elements slowly?

本文关键字:移动 DOM 元素 缓慢 何缓慢      更新时间:2023-09-26

如何缓慢移动DOM元素?不起作用

 for ( var a = 0 ; a < 100 ; a++){
    $('*').each(function(){
      if ( ! /HTML/.test($(this).context.nodeName))
      {
        var top =  parseInt($(this).css('top')) + 1;
        $(this).css('top',top + "px");
      }
    });
  }

当回路完成时,元件已定位

我怎么能慢慢来?

对不起我的英语

或者在纯javascript中,您应该使用计时器

var $elem = $(this), // jquery object
    elem = $elem[0], // dom element
    currentPos = $elem.offset().top, // current position
    targetPos = currentPosition + 100, // target position
    timer = setInterval (function () { // timer to move element slowly
        currentPos++;
        $elem.css('top',currentPosition + "px");
        if (currentPos == targetPos)
            clearInterval(timer);
    }, 100);

尝试jquery的$.animate()

它需要你设置一个目标位置来移动,而不是连续移动

或使用setInterval:

intervalInMilliseconds=17;//60 frames per second
var interval = setInterval(function()
{
for ( var a = 0 ; a < 100 ; a++){
    $('*').each(function(){
      if ( ! /HTML/.test($(this).context.nodeName))
      {
        var top =  parseInt($(this).css('top')) + 1;
        $(this).css('top',top + "px");
      }
    });
  }
},intervalInMilliseconds);

完成以下操作后停止:

clearInterval(interval)

如果你的目标是足够新的浏览器版本,你可以使用CSS动画。