简体   繁体   English

如何在点击时让 div 滚动到页面顶部?

[英]How can I make a div scroll to the top of the page on click?

I have a set of buttons on a page and when someone's clicks I want the button to expand and scroll to the top of the page (viewport height, not the actual top).我在页面上有一组按钮,当有人点击时,我希望按钮展开并滚动到页面顶部(视口高度,而不是实际顶部)。 This is my code -这是我的代码 -

<div class="team-header" id="brian">
    <div class="teamlogo">
        <img src="images/logos/wolves.png" />
        <h1>Brian</h1>
    </div>
  </div>
  <div class="brian-roster team-rosters">
    <?php include ('brian.php'); ?>
  </div>

    <div class="team-header" id="carlos">
    <div class="teamlogo">
        <img src="images/logos/leverkusen.png" />
        <h1>Carlos</h1>
    </div>
  </div>

  <div class="carlos-roster team-rosters">
    <?php include ('carlos.php'); ?>
  </div>

There are 14 of those divs in total, that's just an example of two.总共有 14 个 div,这只是其中两个的示例。

I have this jQuery code for each one -我每个都有这个 jQuery 代码 -

  const brianRoster = $(".brian-roster");
  const brianID = $("#brian");

  brianID.on("click", function () {
    $("html, body").animate(
      {
        scrollTop: $("#brian").offset().top - 60,
      },
      100
    );
    $(brianRoster).slideToggle(700);
  });

(the -60 is to compensate for a sticky header) (-60 是为了补偿粘性标题)

Right now if you click the button it expands but does not scroll to the top.现在,如果您单击按钮,它会展开但不会滚动到顶部。 If you click the button again it collapses (as it should), and then scrolls to the top.如果再次单击该按钮,它会折叠(应该如此),然后滚动到顶部。

How can I get it to scroll to the top?我怎样才能让它滚动到顶部?

try this:尝试这个:

$(window).scrollTop(0); 

instead of代替

scrollTop: $("#brian").offset().top - 60,

or try或尝试

$("html, body").animate(
  {
    scrollTop: $("#brian").offset().top,
  },
   slow
 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM