You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JQuery中同时实现Ready与Hover事件:Div随机移动+悬停避让

解决Div随机移动与鼠标悬停躲开无延迟触发的问题

嘿,我明白你的问题了——你希望那个随机移动的Div在页面加载后,既能立刻开始随机跑动,又能在鼠标一碰到它的时候就马上躲开,不用等初始的随机动画跑完。咱们一步步来修复这个问题:

问题根源

  • 你的选择器写错了:$("myDiv")这种写法是找<myDiv>标签,而不是id或class为myDiv的元素,得改成对应选择器(比如$("#myDiv")或者直接用你已经选中的$('.ciao'))。
  • 当元素正在执行animate动画时,新的动画会加入队列等待,所以hover的躲开效果会被延迟,得先停止当前动画再执行躲开逻辑。
  • 要确保hover事件和随机动画在页面加载后同时生效,不能让hover事件等待动画启动。

修改后的完整代码

$(document).ready(function() {
  const $target = $('.ciao');
  
  // 启动随机移动动画
  animateDiv($target);
  
  // 绑定hover事件:鼠标进入时躲开,离开后继续随机移动
  $target.hover(function(event) {
    // 停止当前动画并清空队列,让躲开效果立刻执行
    $(this).stop(true, false);
    
    // 计算躲开方向:往鼠标反方向移动一段距离
    const mouseX = event.pageX;
    const mouseY = event.pageY;
    const elemOffset = $(this).offset();
    
    // 调整移动距离,可根据需求修改数值
    const newLeft = elemOffset.left > mouseX 
      ? elemOffset.left + 150 
      : elemOffset.left - 150;
    const newTop = elemOffset.top > mouseY 
      ? elemOffset.top + 150 
      : elemOffset.top - 150;
    
    // 执行躲开动画,完成后继续随机移动
    $(this).animate({
      left: newLeft,
      top: newTop
    }, 300, function() {
      animateDiv($(this));
    });
  }, function() {
    // 鼠标快速离开时,确保恢复随机移动
    animateDiv($(this));
  });
  
  // 修正后的点击事件
  $target.click(function() {
    $(this).animate({left: "+=100px"});
  });
});

// 随机位置生成函数
function makeNewPosition($container) {
  const h = $container.height() - 50;
  const w = $container.width() - 50;
  const nh = Math.floor(Math.random() * h);
  const nw = Math.floor(Math.random() * w);
  return [nh, nw];
}

// 随机移动动画函数
function animateDiv($target) {
  const newq = makeNewPosition($target.parent());
  const oldq = $target.offset();
  const speed = calcSpeed([oldq.top, oldq.left], newq);
  $target.animate({
    top: newq[0],
    left: newq[1]
  }, speed, function() {
    animateDiv($target);
  });
}

// 速度计算函数
function calcSpeed(prev, next) {
  const x = Math.abs(prev[1] - next[1]);
  const y = Math.abs(prev[0] - next[0]);
  const greatest = x > y ? x : y;
  const speedModifier = 0.1;
  const speed = Math.ceil(greatest / speedModifier);
  return speed;
}

关键改动说明

  • 选择器修正:把错误的$("myDiv")替换成目标元素$target,确保事件绑定到正确的Div上。
  • hover时强制中断动画:用.stop(true, false)停止当前动画并清空队列,让躲开动画无需等待直接执行。
  • 智能躲开逻辑:通过对比鼠标和元素的位置,让Div往鼠标的反方向移动,你可以根据喜好调整移动距离和动画速度。
  • 无缝恢复随机移动:不管是躲开动画完成后,还是鼠标快速离开,都会重新启动随机移动逻辑,保证流程连贯。

这样修改后,页面加载后Div会立刻开始随机移动,同时鼠标一悬停就能马上触发躲开效果,完全没有延迟啦!

内容的提问来源于stack exchange,提问作者Nicla Marino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:44:54