javascript - 加载后滚动到引导模式中的元素
问题描述
我有一个基于用户通过引导模式访问的文本的多项选择测验。稍后,当他们查看答案并打开模式时,答案的位置会突出显示(通过 ID 定位为 span 元素)。但是,用户必须滚动才能找到位于模态下方的突出显示文本。理想情况下,我希望模态加载后自动向下滚动到这些位置。
我正在使用这段代码在模态加载后滚动,但它不滚动..
$(window).on('shown.bs.modal', function() {
$('#myModal').animate({
scrollTop: $('#D6').position().top + $('#myModal').height()
});
});
任何人都可以建议吗? 这就是活动。
谢谢!
解决方案
这里的问题是试图在 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);
});
推荐阅读
- c# - 无法加载文件或程序集..即使它在正确的位置并且构建良好
- spring - SpringBoot 创建框架启动库
- r - R - 帮助从 0 构建时间列?
- php - 对特定分类有问题循环
- mysql - 数据库架构:当记录具有不同数量的属性(列)
- python - beautifulsoup select 方法返回回溯
- android - 是什么导致 Google Play 开发者控制台中出现此警告:“我们检测到您的应用正在使用旧版本的 Google Play 开发者 API”
- php - 为什么添加标题后无法获取 POSTFIELDS?
- react-native - 如何在本机反应中跨组件全局调用一种方法
- c# - 类型列表参数的正确命名约定