加载后滚动到引导模式中的元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了加载后滚动到引导模式中的元素相关的知识,希望对你有一定的参考价值。

我有一个基于用户通过Bootstrap模式访问的文本的多项选择测验。稍后,当他们检查他们的答案并打开模态时,答案的位置会突出显示(通过ID定位为跨度元素)。但是,用户必须滚动才能找到位于模态下方的突出显示的文本。理想情况下,我希望模态在模态加载后自动向下滚动到这些位置。

我正在使用这段代码在模态加载后滚动,但它不滚动..

$(window).on('shown.bs.modal', function() { 
    $('#myModal').animate({
        scrollTop: $('#D6').position().top + $('#myModal').height()
    });
});

任何人都可以建议吗? This is the activity.

谢谢!

答案

这里的问题是尝试在附加到DOM之前访问html元素(即#D6#myModal)的位置/维度。

解决方案是重构代码,以便在尝试调用.height().position()方法之前,首先将这些元素附加到DOM。

不建议将以下代码作为解决方案,但提供此代码是为了进一步了解问题:

$(window).on('shown.bs.modal', function() { 

    // 1. If #myModal not attached to DOM, calling $('#myModal').height() returns undefined

    // 2. #D6 not attached to DOM, $('#D6').position().top is not defined

    // 3. Performing this arithmetic, $('#D6').position().top + $('#myModal').height(), will therefore be undefined

    // Assuming #D6 and #myModal will be attached to the DOM, delay access to .height() and .position()
    setTimeout( function() { 

        // We're assuming that #D6 and #myModal are now present in the DOM after this delay. If that is the case, the logic below will correctly calculate an offet value for scrollTop, thus achieving the desired effect
        $('#myModal').animate({ 
            scrollTop: $('#D6').position().top + $('#myModal').height() 
        }); 
    }, 100);
});

以上是关于加载后滚动到引导模式中的元素的主要内容,如果未能解决你的问题,请参考以下文章

方向/配置更改后如何维护 ListView 片段状态?

加载 twitter 引导模式对话框时,如何防止正文滚动条和移位?

使用 React useEffect 在页面加载时滚动到元素中的位置

引导加载程序 - 将处理器切换到保护模式

加载数据后如何防止滚动视图滚动到网络视图?

向下滚动到 Fancybox 窗口中的元素(ajax 加载的内容)