Проблема здесь заключалась в попытке доступа к расположению / размеру элементов 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);
});