[英]How to scroll to show a part of a webpage
除了锚点,您还可以使用JavaScript在网络浏览器中控制/读取滚动条的不同方式有哪些? -除非您可以动态创建锚点并告诉浏览器向下滚动到该锚点。
var coord = {top:null,left:null,width:null,height:null};
if (typeof window.pageYOffset == 'number') {
coord.top = window.pageYOffset; coord.left = window.pageXOffset;
} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
coord.top = document.body.scrollTop; coord.left = document.body.scrollLeft;
} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
coord.top = document.documentElement.scrollTop; coord.left = document.documentElement.scrollLeft;
}
if (typeof window.innerWidth == 'number') {
coord.width = window.innerWidth; coord.height = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
coord.width = document.documentElement.clientWidth; coord.height = document.documentElement.clienthHeight;
} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
coord.width = document.body.clientWidth;
coord.height = document.body.clientHeight;
}
滚动任意数量:
//Parameters being the amount by which to scroll in pixels (horizontal and vertical)
window.scrollBy(50, 50);
滚动到某个点:
window.scrollTo(0, 30);
读取当前位置:
document.body.scrollLeft
document.body.scrollTop
使用scrollTop
属性(所有元素的固有属性),您可以滚动到特定的像素高度。 因此,滚动到特定锚点的高度将涉及查询该锚点的偏移量并相应地设置scrollTop
。 仅出于说明目的; 这就是使用jQuery滚动到指定元素的方式:
var top = $('div#something').offset().top;
$(document).scrollTop(top);
注意 :jQuery的实现可能会产生误导; 它接受document
但是具有scrollTop
属性的最顶层元素实际上是document.documentElement
(通常引用<HTML>
)。
还有一个scrollLeft
属性用于水平滚动。
当然,您可以阅读以下属性:
var currentScrollTop = document.documentElement.scrollTop;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.