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

jQuery控制的div在窗口宽度大于768px时无法回到原位置如何修复

问题原因

你的代码仅实现了窗口宽度小于768px时移动目标div的逻辑,没有补充窗口宽度≥768px时将div放回初始位置的对应分支,自然无法复位。

实现步骤
  • 页面加载完成后先在目标div的初始位置插入隐藏的占位符节点,作为复位时的位置锚点,避免div被移走后找不到原始挂载位置。
  • 在resize事件中增加else分支,判断窗口宽度≥768px时将div插回占位符后方的原始位置。
  • 增加位置存在性判断,避免resize事件高频触发时重复执行DOM操作,减少性能损耗。
  • 页面加载完成后主动触发一次resize判断,适配页面刚加载时宽度就小于768px的场景。
修复后完整代码
jQuery(document).ready(function($) {
    const $targetDiv = $('#div_block-61-89');
    // 插入隐藏占位符作为原始位置锚点
    const $positionPlaceholder = $('<div style="display: none;"></div>').insertBefore($targetDiv);

    $(window).resize(function(){
        const winWidth = $(window).width();
        if (winWidth < 768) {
            // 已经在目标容器则不重复操作
            if ($targetDiv.parent().hasClass('offcanvas-inner')) return;
            $targetDiv.detach().prependTo('.offcanvas-inner');
        } else {
            // 已经在原始位置则不重复操作
            if ($targetDiv.prev().is($positionPlaceholder)) return;
            $targetDiv.detach().insertAfter($positionPlaceholder);
        }
    }).trigger('resize'); // 主动触发一次适配初始窗口宽度
});

内容的提问来源于stack exchange,提问作者el matouggui el houssein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:36:03