Way to scroll to a percentage of the page's height?

时间:2015-12-10 01:59:08

标签: javascript

I'm trying to create something like an anchor tag. When a user clicks on a thumbnail, I want to be able to scroll up a bit so that the full size image is in the center of the browser. I've tried scrolling to a specific height, but I noticed that the ideal height changes based on how wide the browser window might be. I'm wondering if I can scroll up to a percentage of the page (say 30% from the top). Is this possible to do in vanilla Javascript? Thanks.

1 个答案:

答案 0 :(得分:0)

获取页面的总高度并计算需要的高度并在scrollTo中使用它。

var body = document.body,
  html = document.documentElement;

var height = Math.max(body.scrollHeight, body.offsetHeight,
  html.clientHeight, html.scrollHeight, html.offsetHeight);


$("#btn2").click(function() {
  $('html, body').animate({
        scrollTop: height * 0.33
    }, 2000);
});

$("#btn3").click(function() {
  $('html, body').animate({
        scrollTop: height * 0.66
    }, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="btn2">33%</button>
<button id="btn3">66%</button>
<div style="height:500px; width:100%;">
  1
</div>
<div style="height:500px; width:100%;">
  2
</div>
<div style="height:500px; width:100%;">
  3
</div>