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

问题描述 投票:0回答:1

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

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

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

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

谢谢!

javascript jquery twitter-bootstrap scroll modal-dialog
1个回答
0
投票

这里的问题是尝试在附加到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);
});
© www.soinside.com 2019 - 2024. All rights reserved.