.next() jQuery 只滚动一次



最好只是检查小提琴并尝试单击按钮。

我遇到的问题是第一个按钮可以使用 jQuery .next() 函数导航到下一部分。但是,它不适用于其余部分。

var buttons= document.querySelectorAll(".next-section");
for(var i=0; i<buttons.length; i++){
    buttons[i].addEventListener("click", scrollDown);
}   
function scrollDown(){
    console.log("Debug: BUTTON CLICKED")
    $('html, body').animate({
        scrollTop: $("section").next(".page").offset().top 
    }, 'slow');
}

您的事件附件有效,并且正在调用scrollDown方法。

但是,$("section").next(".page")始终返回第二页,并始终尝试将页面滚动到第二部分。

发生什么:

  1. $("section")返回页面的所有section元素(第 1、2、3、4 页(
  2. .next(".page") 返回每个元素的下一页(第 2、3、4 页(
  3. .offset().top返回列表中第一个元素的顶部位置(第 2 页(

相反,您需要获取当前页面的下一页,该页面$(this).closest(".page"),并获取其偏移量。
您可以改用以下代码:

$('html, body').animate({
    scrollTop: $(this).closest(".page").next().offset().top 
}, 'slow');

这是工作演示:

var buttons = document.querySelectorAll(".next-section");
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", scrollDown);
}
function scrollDown() {
  console.log("Debug: BUTTON CLICKED")
  $('html, body').animate({
    scrollTop: $(this).closest(".page").next().offset().top
  }, 'slow');
}
html,
body {
  text-align: center;
  margin: 0;
}
.page {
  height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.content {
  display: block;
  height: auto;
}
#one {
  background-color: grey;
}
#two {
  background-color: red;
}
#three {
  background-color: blue;
}
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link rel="stylesheet" type="text/css" href="./css/styles.css">
</head>
<body>
  <section class="page" id="one">
    <div class="content">
      <h1>Page1</h1>
      <p>This is page 1</p>
      <button class="next-section">Next Page!</button>
    </div>
  </section>
  <section class="page" id="two">
    <div class="content">
      <h2>PAGE 2</h2>
      <button class="next-section">Next Page</button>
    </div>
  </section>
  <section class="page" id="three">
    <div class="content">
      <h2>PAGE 3</h2>
      <button class="next-section">Next Page</button>
    </div>
  </section>
  <section class="page" id="four">
    <div class="content">
      <h2>PAGE 4</h2>
      <button class="next-section">Next Page</button>
    </div>
  </section>

  <script type="text/javascript" src="./js/script.js"></script>
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</body>
</html>

一个小的改进建议:不要混合使用vanilla JS事件和jQuery。
如果你使用jQuery,那么使用$(".next-section").click(scrollDown)而不是document.querySelectorAlladdEventListener

最新更新