Moving Div with Scroll

放肆的年华 提交于 2019-11-27 15:04:22

问题


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 :-).


回答1:


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
}


来源:https://stackoverflow.com/questions/5616335/moving-div-with-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!