简体   繁体   English

如何在Javascript中滚动半页

[英]How to scroll half page in Javascript

Using this native javascript method: 使用本机javascript方法:

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 . 要获取文档的高度而不是窗口的高度,您需要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. 如果需要整个页面的高度,请选择<body>标签并获取其高度。 Note that getElementsByTagName returns an array. 请注意, getElementsByTagName返回一个数组。

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

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

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