首页 > 解决方案 > 如何滚动到第一个子 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');
    };
  });
});

到目前为止,我没有成功地尝试:

  1. 给子 div 我要定位一个类,然后滚动到该类的第一个子 div,如下所示:
$('html, body').animate({
    scrollTop: $('.class:visible:first').offset().top
}, 1000);
  1. 在当前滚动代码后添加return, false;如下:
$('html, body').animate({
    scrollTop: $target.offset().top - 128
}, 2000); return, false;
  1. 使用 :first 选择器,如下所示:
$( "$target:first" )`
  1. 将“滚动代码”放在循环之外,通过单独的
$('#index_year p, section p').on('click', function() {
    $('html, body').animate({
        scrollTop: $target.offset().top - 128
    }, 2000);
});
  1. 补充一下scrollIntoView,我只是无法想象在哪里以及如何使用它。

到目前为止,它不适合我,我正在寻求帮助。

标签: javascriptjqueryhtmlcss

解决方案


我会将具有“年份”类的第一幅画存储在另一个变量中,以便在循环后继续滚动。

但是具有匹配日期的每个部分的动画必须在循环中......

$('#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);

  }
});

推荐阅读