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

页面滚动至底部时cursor_div无法跟随光标定位问题求助

自定义光标滚动后位置偏移问题

页面处于顶部时,cursor和cursor_border能正常跟随光标,但滚动至页面底部后,两个元素的位置无法正确匹配光标位置。

现有代码

HTML(已修正语法错误):

<div id="cursor"></div>
<div id="cursor_border"></div>

JavaScript:

var cursor = $('#cursor');
var cursor_border = $('#cursor_border');

$(document).mousemove(function(e){
    console.log(e.pageY + ' and '+ e.pageX ) ;
    var x = e.pageX;
    var y = e.pageY;
    cursor.css("left",x+'px');
    cursor.css("top",y+'px');
    cursor_border.css("left",x+'px');
    cursor_border.css("top",y+'px');
});

问题原因

核心问题是光标坐标与元素定位属性不匹配:

  • e.pageX/pageY是光标相对于整个文档的坐标,包含了页面已滚动的距离。
  • 如果你的光标元素使用position: fixed(自定义光标准常用法),top/left是相对于当前视口的,此时用pageX/pageY会把滚动偏移量算进去,导致滚动后位置错位。

解决方案

方案1:使用position: fixed(推荐)

改用e.clientX/clientY获取光标相对于视口的坐标,同时给元素添加fixed定位:

CSS:

#cursor, #cursor_border {
    position: fixed;
    pointer-events: none; /* 避免遮挡其他元素交互 */
    /* 根据需求添加宽高、背景、圆角等样式 */
}

JavaScript:

var cursor = $('#cursor');
var cursor_border = $('#cursor_border');

$(document).mousemove(function(e){
    const x = e.clientX;
    const y = e.clientY;
    // 批量设置样式更简洁
    cursor.css({ left: `${x}px`, top: `${y}px` });
    cursor_border.css({ left: `${x}px`, top: `${y}px` });
});

方案2:使用position: absolute(仅当必须使用时)

如果必须用absolute定位,需要减去页面的滚动偏移量,修正坐标:

CSS:

#cursor, #cursor_border {
    position: absolute;
    pointer-events: none;
}

JavaScript:

var cursor = $('#cursor');
var cursor_border = $('#cursor_border');

$(document).mousemove(function(e){
    const scrollX = $(window).scrollLeft();
    const scrollY = $(window).scrollTop();
    const x = e.pageX - scrollX;
    const y = e.pageY - scrollY;
    
    cursor.css({ left: `${x}px`, top: `${y}px` });
    cursor_border.css({ left: `${x}px`, top: `${y}px` });
});

额外注意

原HTML存在语法错误(#cursor标签未闭合,#cursor_border前多了一个</div>),已在代码中修正,错误的标签结构可能导致元素布局异常,务必保证标签正确闭合。

内容的提问来源于stack exchange,提问作者Kevin Webster Revalde

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:20:15