首页 > 解决方案 > 加载后滚动到引导模式中的元素

问题描述

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

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

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

任何人都可以建议吗? 这就是活动。

谢谢!

标签: javascriptjquerytwitter-bootstrapscrollmodal-dialog

解决方案


这里的问题是试图在 HTML 元素(即#D6#myModal)附加到 DOM 之前访问它们的位置/尺寸。

解决方案是重构代码,使这些元素首先附加到 DOM,然后再尝试调用它们的.height().position()方法。

不推荐使用以下代码作为解决方案,但提供以下代码是为了进一步了解问题:

$(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);
});

推荐阅读