我的目标是多个容器 div 中的多个相似的子 div。随后页面滚动到第一个目标子 div。
不幸的是,页面没有滚动到第一个子 div 然后停止滚动。页面会一个接一个地滚动到所有子 div。
不幸的是,我正在尝试改变这种行为。我希望页面在第一个子 div 处停止滚动。
要查看我的实际问题,请单击标题中的任意年份:http://paintings.directory
当前的 jQuery 代码:
var $sections = $('section');
$('#index_year p, section p').on('click', function(e) {
let year = $(this).data('y');
$sections.each(function() {
let $section = $(this);
let $target = $('.' + year, $section);
if ($target.length) {
$('html, body').animate({
scrollTop: $target.offset().top - 128
}, 2000);
$section.removeClass('yearNotFound');
$section.animate({
scrollLeft: $section.scrollLeft() + $target.position().left
}, 2000);
} else {
$section.addClass('yearNotFound');
};
});
});
到目前为止,我没有成功地尝试过:
- 给我的子 div 我定位一个类,然后滚动到具有该类的第一个子 div,如下所示:
$('html, body').animate({
scrollTop: $('.class:visible:first').offset().top
}, 1000);
- 在当前滚动代码后添加
return, false;
如下:
$('html, body').animate({
scrollTop: $target.offset().top - 128
}, 2000); return, false;
- 使用 :first 选择器如下:
$( "$target:first" )`
- 将“滚动代码”放在循环之外,通过单独制作
$('#index_year p, section p').on('click', function() {
$('html, body').animate({
scrollTop: $target.offset().top - 128
}, 2000);
});
- 添加
scrollIntoView
,我只是无法想象在哪里以及如何使用它。
到目前为止,它对我来说没有用,因此我正在寻求帮助。
最佳答案
我会将具有“年”类的第一幅画存储在另一个变量中,以便在循环后继续滚动。
但是具有匹配日期的每个部分的动画必须在循环中......
$('#index_year p, section p').on('click', function(e) {
let year = $(this).data('y');
var $storedTarget;
$sections.each(function() {
let $section = $(this);
let $target = $('.' + year, $section);
if ($target.length) {
// Store the target here.
if(typeof($storedTarget) == "undefined"){
$storedTarget = $target.first(); // The first one!
}
// Animate sections left/right if there's a match
$section.animate({
scrollLeft: $section.scrollLeft() + $target.position().left
}, 1500);
$section.removeClass('yearNotFound');
} else {
$section.addClass('yearNotFound');
}
});
// Make sure there is at least a result..
if($storedTarget.length>0){
// Scrolling to the first section that has a match
$('html, body').animate({
scrollTop: $storedTarget.offset().top - 128
}, 1500);
}
});
关于javascript - 如何滚动到第一个子 div,而不是一个接一个地滚动到所有目标子 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507130/