用滚动移动Div [英] Moving Div with Scroll

查看:122
本文介绍了用滚动移动Div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当滚动条移动时,我必须移动div,但需要使用纯javascript,并且position:fixed将无法与布局一起使用。该div的原始渠道是相对于其他东西。是否有一个简单的实现使用像onScroll这样的事件来检测页面向上或向下移动的像素数量,并相应地更改div的位置。 div只需要垂直移动。所以,如果我可以检测到页面移动了多少像素,我可以将其添加到div的位置或将其减去。任何帮助是极大的赞赏 :-)。

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

推荐答案

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
}

这篇关于用滚动移动Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆