繁体   English   中英

加载后滚动到引导程序模态中的元素

[英]Scrolling to an element in a bootstrap modal after loading

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

我正在使用此代码块在模态加载后滚动,但它不会滚动。

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

有人可以建议吗? 这是活动。

谢谢!

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

解决方案是重新组织代码,以使这些元素在尝试调用它们的.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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM