Javascript 使用滚动移动 Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5616335/
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
Moving Div with Scroll
提问by rubixibuc
I have to move a div when the scroll bar moves, but need to use pure javascript, and position:fixed will not work with the layout. The div's original poisition is relative to something else. Is there a simple implementation using and event like onScroll, to detect how many pixels the page moved up or down, and change the position of the div accordingly. The div only needs to move vertically. So if I can detect how many pixels the page has moved I can just add or subtract that to the location of the div. Any help is greatly appreciated :-).
我必须在滚动条移动时移动一个 div,但需要使用纯 javascript,而 position:fixed 不适用于布局。div 的原始位置是相对于其他东西的。是否有一个简单的实现,使用像 onScroll 这样的事件来检测页面向上或向下移动了多少像素,并相应地更改 div 的位置。div 只需要垂直移动。因此,如果我可以检测到页面移动了多少像素,我可以将其添加或减去 div 的位置。任何帮助是极大的赞赏 :-)。
回答by Jake
window.onscroll = function (e) {
var vertical_position = 0;
if (pageYOffset)//usual
vertical_position = pageYOffset;
else if (document.documentElement.clientHeight)//ie
vertical_position = document.documentElement.scrollTop;
else if (document.body)//ie quirks
vertical_position = document.body.scrollTop;
var your_div = document.getElementById('some_div');
your_div.top = (vertical_position + 200) + 'px';//200 is arbitrary.. just to show you could now position it how you want
}