admin管理员组

文章数量:1328564

I am trying to implement a simple button that on click will scroll the page either up or down 100vh between my sections. I can see plenty of examples doing this with jQuery but I'm looking for a pure javascript solution. I'm not to sure how to achieve it.

Appreciate any advice.

HTML

<section class="section section-1">
  <div class="btn"></div>
</section>
<section class="section section-2">
  <div class="btn"></div>
</section>
<section class="section section-3">
  <div class="btn"></div>
</section>

CSS

.section {
  width: 100%;
  height: 100vh:
}

This is what I have e up with so far

for (var s = 0; s < btn.length; s++) {
    btn[s].addEventListener('click', function(){
        window.scrollBy(0,1000);
    });
}

I am trying to implement a simple button that on click will scroll the page either up or down 100vh between my sections. I can see plenty of examples doing this with jQuery but I'm looking for a pure javascript solution. I'm not to sure how to achieve it.

Appreciate any advice.

HTML

<section class="section section-1">
  <div class="btn"></div>
</section>
<section class="section section-2">
  <div class="btn"></div>
</section>
<section class="section section-3">
  <div class="btn"></div>
</section>

CSS

.section {
  width: 100%;
  height: 100vh:
}

This is what I have e up with so far

for (var s = 0; s < btn.length; s++) {
    btn[s].addEventListener('click', function(){
        window.scrollBy(0,1000);
    });
}
Share Improve this question asked Jun 6, 2018 at 15:08 LiamLiam 1112 gold badges6 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

There are a few ways to get viewport size in JavaScript. Using one of these ways, you should be able to scroll as you are with the viewport size in place of your 1000.

For instance, if I wanted to scroll exactly the height of one viewport with window.innerHeight:

let pageHeight = window.innerHeight;
window.scrollBy(0, pageHeight);

document.querySelectorAll('.btn').forEach(btn => {
  btn.addEventListener('click', function() {
    let scrollDistance = document.documentElement.clientHeight;
    if (btn.className.split(' ').includes('scroll-up')) {
      scrollDistance *= -1;
    }
    window.scrollBy(0, scrollDistance);
  });
});
body {
  margin: 0;
}

.section {
  width: 100%;
  height: 100vh;
}

.section-1 {
  background-color: blue;
}

.section-2 {
  background-color: red;
}

.section-3 {
  background-color: green;
}
<section class="section section-1">
  <div class="btn scroll-down">V</div>
  <div class="btn scroll-up">^</div>
</section>
<section class="section section-2">
  <div class="btn scroll-down">V</div>
  <div class="btn scroll-up">^</div>
</section>
<section class="section section-3">
  <div class="btn scroll-down">V</div>
  <div class="btn scroll-up">^</div>
</section>

本文标签: On click scroll up or down 100vh pure javascriptStack Overflow