简体   繁体   English

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

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

I have a multiple choice quiz based on a text that the user accesses via a Bootstrap modal. 我有一个基于用户通过Bootstrap模式访问的文本的多项选择测验。 Later when then they review their answers and open the modal, the locations of the answers appear highlighted (targeted as span elements via ID). 之后,当他们查看其答案并打开模态时,答案的位置将突出显示(通过ID定位为跨度元素)。 However, the user has to scroll to find highlighted text that is positioned lower down the modal. 但是,用户必须滚动才能找到位于模式下方的突出显示的文本。 Ideally I want the modal to scroll down to these locations automatically after the modal loads. 理想情况下,我希望模态在加载模态后自动向下滚动到这些位置。

I'm using this block of code to scroll after the modal loads, but it doesn't scroll.. 我正在使用此代码块在模态加载后滚动,但它不会滚动。

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

Can anyone advise? 有人可以建议吗? This is the activity. 这是活动。

Thanks! 谢谢!

The problem here was an attempt to access the postion/dimension of HTML elements (ie #D6 and #myModal ) before they were attached to the DOM. 这里的问题是试图将HTML元素(即#D6#myModal )附加到DOM之前访问它们的位置/尺寸。

The solution is to restructure the code, such that those elements are attached to the DOM first, before trying to call their .height() or .position() methods. 解决方案是重新组织代码,以使这些元素在尝试调用它们的.height().position()方法之前先附加到DOM。

The code below is not recommended as a solution, but is provided to give futher insight to the problem: 不建议将以下代码作为解决方案,但提供该代码可以进一步了解该问题:

$(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