当用户滚动时,我必须移动一个 div,但需要使用纯 JavaScript。
position: fixed;
不适用于布局。div 的原始位置是相对于其他东西的。是否有使用类似事件的简单实现onscroll
,以检测页面向上或向下移动了多少像素,并相应地更改 div 的位置?
div 只需要垂直移动。因此,如果我可以检测到页面移动了多少像素,我可以将其添加或减去 div 的位置。
当用户滚动时,我必须移动一个 div,但需要使用纯 JavaScript。
position: fixed;
不适用于布局。div 的原始位置是相对于其他东西的。是否有使用类似事件的简单实现onscroll
,以检测页面向上或向下移动了多少像素,并相应地更改 div 的位置?
div 只需要垂直移动。因此,如果我可以检测到页面移动了多少像素,我可以将其添加或减去 div 的位置。
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.style.top = (vertical_position + 200) + 'px';//200 is arbitrary.. just to show you could now position it how you want
}