最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I move a div on scroll? - Stack Overflow

programmeradmin3浏览0评论

I have to move a div when the the user scrolls, but need to use pure JavaScript.

position: fixed; will not work with the layout. The div's original position is relative to something else. Is there a simple implementation using an 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.

I have to move a div when the the user scrolls, but need to use pure JavaScript.

position: fixed; will not work with the layout. The div's original position is relative to something else. Is there a simple implementation using an 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.

Share Improve this question edited Jul 8, 2021 at 9:37 double-beep 5,50419 gold badges40 silver badges48 bronze badges asked Apr 11, 2011 at 2:51 rubixibucrubixibuc 7,39722 gold badges64 silver badges106 bronze badges 1
  • 1 So what you have by now is... (this is where you paste a code snippet you've done so far) – Francisco Alvarado Commented Apr 11, 2011 at 3:00
Add a comment  | 

1 Answer 1

Reset to default 18
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
}
发布评论

评论列表(0)

  1. 暂无评论