首页
/ jQuery UI Datepicker 在滚动后定位异常的解决方案

jQuery UI Datepicker 在滚动后定位异常的解决方案

2025-05-20 11:04:00作者:管翌锬

问题背景

在使用jQuery UI 1.13.2和jQuery 3.7.1版本时,开发者发现当页面滚动后,在Bootstrap模态框中打开的Datepicker组件会出现定位异常的问题。具体表现为Datepicker弹出窗口不会正确显示在输入框下方,而是出现在错误的位置。

问题分析

这个问题源于jQuery UI Datepicker组件内部计算偏移量的逻辑存在缺陷。当页面发生滚动且Datepicker在固定定位的模态框中打开时,原始的_checkOffset方法没有正确处理滚动偏移量,导致定位计算错误。

解决方案

通过重写Datepicker的_checkOffset方法可以解决这个问题。以下是完整的解决方案实现:

$(document).ready(function () {
    setTimeout(function () {
        // 重写_checkOffset函数
        $.datepicker._checkOffset = function (inst, offset, isFixed) {
            var dpWidth = inst.dpDiv.outerWidth(),
                dpHeight = inst.dpDiv.outerHeight(),
                inputWidth = inst.input ? inst.input.outerWidth() : 0,
                inputHeight = inst.input ? inst.input.outerHeight() : 0,
                viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
                viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());

            offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
            offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;

            // 关键修改:正确处理滚动偏移量
            offset.top -= (isFixed && ($(document).scrollTop() > 0)) ? $(document).scrollTop() : 0;

            // 检查Datepicker是否超出视口范围,如果是则调整位置
            offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
                Math.abs(offset.left + dpWidth - viewWidth) : 0);
            offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
                Math.abs(dpHeight + inputHeight) : 0);

            return offset;
        };
    }, 100);
});

实现说明

  1. 延迟执行:使用setTimeout确保代码在Datepicker组件加载完成后执行,避免覆盖失败。

  2. 关键修改点

    • 原始代码仅当offset.top等于输入框底部位置时才减去滚动偏移量
    • 修改后的代码在任何滚动情况下都会正确处理滚动偏移量
  3. 范围检查:保留原始方法中对视口范围的检查逻辑,确保Datepicker不会显示在可视区域之外。

  4. RTL支持:保留对从右到左布局的支持。

部署建议

登录后查看全文

热门内容推荐