当我向下滚动页面时,如何让div跟随我? [英] How do I make a div follow me as I scroll down the page?

查看:682
本文介绍了当我向下滚动页面时,如何让div跟随我?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户输入网站。

此时,div位于页面中间。

At this point, the div is in the middle of the page.

当他向下滚动页面时,div保持靠近顶部,

As he scrolls further down the page, the div stays near the top, always visible to the user.

当他将页面一直向上滚动到顶端时,div会再次停留在最初的位置。

As he scrolls up the page all the way to the top, the div once again stays back in position where it was originally.

推荐答案

您可以在窗口挂钩 scroll 对象。处理事件时,请查看窗口/文档的垂直滚动位置(请参阅这个答案对SO如何做)。对 div 使用绝对定位,并根据需要更新其顶部作为坐标。

You can hook the scroll event on the window object. When processing the event, look at the vertical scroll position of the window/document (see this answer on SO for how to do that). Use absolute positioning for your div and update its top as coordinate as necessary.

FWIW,我会非常小心这样做。通常当用户滚动时,这是因为他们想要查看不同的内容,而不是页面上的内容。就我个人而言,我讨厌在网页上跟随我的盒子。

FWIW, I would be very careful doing this. Usually when a user scrolls, it's because they want to look at different content than what's on the page. Personally, I hate boxes that follow me around on web pages. :-) But that doesn't mean there isn't a good reason for doing this on occasion.

非常基本的例子(复制):

CSS:

#box {
  /* Position absolutely, 30px down from the top */
  position: absolute;
  top: 30px;

  /* In my case I'm centering it in the window; do what you like */
  margin-left: -100px;
  left: 50%;
  width: 200px;

  /* These are just for my example */
  height: 1.25em;
  border: 1px solid #bbb;
  text-align: center;
}

HTML:

<div id='box'>I'm the box</div>

JavaScript:

JavaScript:

window.onload = function() {

  function getScrollTop() {
    if (typeof window.pageYOffset !== 'undefined' ) {
      // Most browsers
      return window.pageYOffset;
    }

    var d = document.documentElement;
    if (d.clientHeight) {
      // IE in standards mode
      return d.scrollTop;
    }

    // IE in quirks mode
    return document.body.scrollTop;
  }

  window.onscroll = function() {
    var box = document.getElementById('box'),
        scroll = getScrollTop();

    if (scroll <= 28) {
      box.style.top = "30px";
    }
    else {
      box.style.top = (scroll + 2) + "px";
    }
  };

};

(在我的例子中,我总是把它保持在顶部以下2个像素,不想要你可以相应地调整数字。)

(In my case, I'm always keeping it 2 pixels below the top, but if you don't want that you can adjust the numbers accordingly.)

这篇关于当我向下滚动页面时,如何让div跟随我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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