javascript - 如何滚动到第一个子 div,而不是一个接一个地滚动到所有目标子 div?

标签 javascript jquery html css

我的目标是多个容器 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,我只是无法想象在哪里以及如何使用它。

到目前为止,它对我来说没有用,因此我正在寻求帮助。

最佳答案

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

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

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

相关文章:

javascript - if else 子句中 undefined object 的未定义属性

javascript - 如何在 three.js 中从 BufferGeometry 绘制 2D/3D 网格

PHP 提交问题,变量改变?

javascript - Cakephp 3.1 JavaScript

javascript - 如何将数组附加到下拉导航栏并禁用其中的一个选项

Javascript:将链接文本更改为新文本填充或收缩文本以保持其与原始文本的大小相同

html - Bootstrap 4 : Vertically center badge with utilities only

javascript - 如何更好地识别 AngularJS 中的异常来源

javascript - 如何在图表js中将x轴标签最小化为一天的时间

javascript - tinyMce 绑定(bind) focusin/focusout 事件?