javascript - 如何滚动到第一个子 div,而不是一个接一个地滚动到所有目标子 div?
问题描述
我的目标是多个容器 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);
}
});
推荐阅读
- python-3.x - Pandas 将值与前几行的平均值进行比较
- swift - typealias 可以编码吗?
- r - R 错误地将数值识别为日期并将其转换为数值会导致较大的负值
- laravel - 无法授权或获取令牌
- android - 颤振步骤验证
- php - 不均匀的内容在 Wordpress 中自动居中
- android - 为什么当我尝试访问其过滤器时我的适配器未解析
- php - PHPWord - 如何将单词公式呈现为 html
- kotlin - 将协程上下文显式传递给异步调用会产生不同的异常处理行为与将其安装在封闭范围内
- pyspark - PYSPARK - 读取、转换和拆分 EBCDIC Mainframe 文件到 DataFrame