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

如何将mousemove事件限制在页面中间的指定div区域?

如何将mousemove事件限制在页面中间的特定div区域内?

要实现这个需求,你需要调整事件绑定的目标,并添加边界限制逻辑,确保跟随鼠标的元素不会超出指定区域。具体修改如下:

1. 准备HTML结构

首先在页面中定义那个中间的特定限制区域:

<!-- 页面中间的限制区域,可根据需求调整宽高、样式 -->
<div class="restricted-area" style="width: 600px; height: 400px; margin: 20px auto; border: 1px solid #ccc;"></div>
<!-- 需要跟随鼠标的元素 -->
<div class="title">跟随鼠标的标题</div>

2. 修改JavaScript代码

// 合并条件判断,避免语法歧义
if (window.screen.width > 765 && matchMedia('(pointer:fine)').matches) {
  $(document).ready(function() {
    const restrictedArea = $(".restricted-area");
    const titleEl = $(".title");
    // 获取限制区域的位置、宽高信息
    let areaRect = restrictedArea[0].getBoundingClientRect();
    // 获取跟随元素的自身尺寸
    const titleWidth = titleEl.width();
    const titleHeight = titleEl.height();

    // 只监听限制区域内的mousemove事件
    restrictedArea.on("mousemove", function(e) {
      // 计算鼠标在限制区域内的相对坐标
      let x = e.pageX - areaRect.left;
      let y = e.pageY - areaRect.top;

      // 边界限制:确保元素不会超出限制区域范围
      x = Math.max(0, Math.min(x, areaRect.width - titleWidth));
      y = Math.max(0, Math.min(y, areaRect.height - titleHeight));

      // 更新元素位置
      titleEl.css({
        position: 'absolute',
        left: `${areaRect.left + x}px`,
        top: `${areaRect.top + y}px`
      });
    });

    // 可选:窗口大小改变时重新获取限制区域的位置信息,避免位置偏移
    $(window).on('resize', function() {
      areaRect = restrictedArea[0].getBoundingClientRect();
    });
  });
}

关键说明

  • 事件范围限制:把mousemove事件绑定到目标div(.restricted-area)上,只有鼠标在该区域内移动时才会触发事件,从根源上缩小了触发范围。
  • 边界校验:通过getBoundingClientRect()获取限制区域的位置和尺寸,结合跟随元素自身的宽高,使用Math.max和Math.min确保元素的边缘不会超出限制区域。
  • 修复原代码问题:合并了原代码中两个独立的if语句并添加大括号,避免语法歧义导致的逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:17:44