javascript 如何使用Javascript将窗口移动x个像素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6147168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to move the window by x number of pixels using Javascript
提问by dave
How do I scroll a window or webpage down using Javascript? Basically, I want to move the web page down by certain number of pixels, using Javascript is there any way of doing that?
如何使用 Javascript 向下滚动窗口或网页?基本上,我想将网页向下移动一定数量的像素,使用 Javascript 有没有办法做到这一点?
回答by ninjagecko
You can use the following function:
您可以使用以下功能:
window.scrollBy(x,y)
e.g.
例如
window.scrollBy(0,100)
Since you expressed interest in the "units" (I assume you mean width and height, since the units here are pixels!) if a window is resized:
由于您表示对“单位”感兴趣(我假设您的意思是宽度和高度,因为这里的单位是像素!)如果调整窗口大小:
document.height
1527
window.innerHeight
912
" awesome. But is there anyway to scroll based on if window has been resized? "
“太棒了。但是无论如何都可以根据窗口是否已调整大小来滚动?”
Yes, you can use this event handler:
是的,您可以使用此事件处理程序:
window.onresize = function() {
window.scrollBy(..., ...);
}
回答by djlumley
I've always used jQuery to do this before so if you're interested. . .
我以前一直使用 jQuery 来做这件事,所以如果你有兴趣的话。. .
The viewport can be scrolled with using scrollTop ( http://api.jquery.com/scrollTop/):
可以使用 scrollTop ( http://api.jquery.com/scrollTop/)滚动视口:
$(window).scrollTop(value)
You can find the current offset of an element using offset ( http://api.jquery.com/offset):
您可以使用 offset ( http://api.jquery.com/offset)找到元素的当前偏移量:
$(element).offset().top
and you can find out the window's current scroll through scrollTop too:
您也可以通过 scrollTop 找出窗口的当前滚动:
$(window).scrollTop()
Using those methods you're able to find out the current window's scroll position, determine where you want to scroll to, and scroll from one section to the other using scrollTop, or if you wanted it to be smooth and animated over time — animate ( http://api.jquery.com/animate).
使用这些方法,您可以找出当前窗口的滚动位置,确定要滚动到的位置,并使用 scrollTop 从一个部分滚动到另一部分,或者如果您希望它随着时间的推移变得平滑和动画 — 动画 ( http://api.jquery.com/animate)。
If you wanted to do an event based on browser resize, then you'd simple bind a function to the resize event:
如果您想根据浏览器调整大小执行事件,则只需将函数绑定到调整大小事件:
$(window).bind('resize', myfunction);