简体   繁体   中英

How to scroll half page in Javascript

Using this native javascript method:

window.scrollTo(500, 0);

How do I set my arguments to make it scroll to only half the page?

To get the document's height instead of window height, you need document.body.scrollHeight .

 function scrollHalf(){ window.scrollTo(0, document.body.scrollHeight / 2); } 
 body{ height: 3000px; background: #0fc0fc; } body:before{ top: 50%; height: 10px; background: orangered; content: ' '; width: 100%; display: block; position: relative; } 
 <button onClick = 'scrollHalf()'> Scroll </button> 

 window.scrollTo(0, window.innerHeight / 2); 

了解更多: https : //developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

If you need the height of the entire page, select the <body> tag and get the height of it. Note that getElementsByTagName returns an array.

document.getElementsByTagName('body')[0].offsetHeight

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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