【问题标题】:Scroll to section in HTML/CSS滚动到 HTML/CSS 中的部分
【发布时间】:2022-01-01 22:01:29
【问题描述】:

如果我有以下 JS 代码:

 //Scroll Down button
    $(window).scroll(function () {
    if ($(this).scrollDown() > 100) {
      $('.containerScroll').fadeIn('slow');
    } else {
      $('.containerScroll').fadeOut('slow');
    }
  });

  $('.containerScroll').click(function () {
    $('html, body').animate({
      scrollTop: 0
    }, 1500, 'easeInOutExpo');
    return false;
  });

这基本上是用于返回按钮动画,如果用户单击按钮,那么它会将用户带回主页并平滑滚动。我想要相反的。有没有办法修改上面的 JS 代码,以便当用户单击按钮时,它会将用户带到他们想要的任何页面?现在,它一直滚动到顶部,只将用户带到网站的主页,但我怎样才能让它将用户带到网站上的任何页面?

这是我在 HTML 文件中的内容:

<a href="#about" class="containerScroll">
      <div class="first-scroll"></div>
      <div class="second-scroll"></div>
      </a>

基本上,我希望用户进入页面的“关于”部分而不是主页。有关如何完成此任务的任何建议?

【问题讨论】:

    标签: javascript html jquery css


    【解决方案1】:

    您可以将 scrollTop 值设置为您想要的任何元素的偏移量。例如:

    $('html, body').scrollTop($('#about').offset().top);
    

    将通过获取其偏移量将 scrollTop 设置为 ID 为 about 的元素的顶部。

    或者您可以像在示例中那样使用 animate:

    $('html, body').animate({
        'scrollTop': $('#about').offset().top
    }, 1500);
    

    Fiddle

    Fiddle smooth scroll

    【讨论】:

    • 你能分享整个工作代码吗,比如添加一些缺失的部分......等等?
    • 添加了 JSFiddle。
    • 嗯,虽然滚动不流畅
    • 使用第二个示例进行平滑滚动。
    • 我添加了自己的类,而不是'scrollTop',对吗?
    【解决方案2】:

    到顶部

    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
    

    到元素

    const element = getElementById("someElement");
    //you can do it by jquery. no matter
    element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
    

    MDM:scrolIntoView

    MDM:scrollTo

    【讨论】:

    • 我想滚动到关于页面,所以我要添加一个ID来代替"someElement",然后将它添加到HTML中吗?
    • 是的。您可以在页面的 about 部分添加一些 id,然后滚动到它。
    猜你喜欢
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多