当滚动页面时,将对象固定在浏览器窗口顶部

25

我最近在新版Gmail和HTML5 bing预览中看到了一个有趣的新功能,它可以在滚动时将导航栏固定在浏览器窗口的顶部。该导航栏可能从页面上方100像素处开始,但当您滚动并使其到达浏览器窗口顶部时,它会固定在那里,直到您再次向上滚动到原来的位置。

我的问题是:如何实现这种效果或类似的效果?

希望您能理解我的问题以及我所描述的内容。

8个回答

21

如果你想让元素在页面往下滚动时保持固定在顶部,可以使用以下代码作为起点:

http://jsfiddle.net/cc48t/


4
这个解决方案在每个浏览器中闪烁得很厉害。现代大多数浏览器都支持 position:fixed,这是CSS内置的方法来实现这个效果。 - sohtimsso1970
是的,我不再使用这个解决方案了。那是基于我当时有限的设置固定位置的知识。使用 position: fixed 的解决方案更好。 - g_thom

18

我知道这篇文章有点旧了,但仍然非常有用。我只是想添加一个jQuery版本(更简洁和可配置),但这是Andrew D.答案的修改版。

在这种情况下,我没有两个类,而是有一个相对定位的div,当我到达某个点(max_scroll)时,我会向对象添加一个类,而该类就是使其浮动的原因。

以下是JavaScript代码(全部在文档准备好函数内完成):

<script type="text/javascript">
var max_scroll = 400; // this is the scroll position to start positioning the nav in a fixed way
$(document).ready(function(){

        $(window).scroll(function () {
        var navbar = $(".filterbutton");

        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        if(scrollTop > max_scroll && !navbar.is(".filterbuttonFixed")) {
                navbar.addClass("filterbuttonFixed");
                // console.log("go floated");
        }
        else if(scrollTop < max_scroll && navbar.is(".filterbuttonFixed") ) {
                // console.log("return to normal");
                navbar.removeClass("filterbuttonFixed");
        }

}
});

</script>

这是我的导航栏容器 div 元素。

<div id="floatable-nav-bar" class="my-relative-position-class">
    <nav class="page-menu">
        <ul class="scroll-nav">
            <li><a class="selected" href="#first">Section 1</a></li>
            <li><a class="" href="#second">Section 2</a></li>
            <li><a class="" href="#third">Section 3</a></li>
            <li><a class="" href="#fourth">Section 4</a></li>
        </ul>
    </nav>
</div>

最后但同样重要的是我的导航浮动样式

#floatable-nav-bar.nav_floated {
    position:fixed;
    top:1px;
    left: 0;
    width:100%;
    text-align: center;
    background: #EEE;
    padding: 5px 0;
}

我知道这并不是最简单的例子,但对于 jQuery 用户来说,也许这是一种更简单的方法,而且我认为只添加和删除一个类别更好(至少对我来说是这样)。


4
轻微建议:您可以使用 max_scroll = $("#floatable-nav-bar").position().top,而不是 max_scroll = 450。这样,当导航栏到达顶部时,它将自动浮动(使用 jQuery 查找顶部偏移量可以解决不同浏览器之间的微小差异)。 - Geoffrey Booth
我喜欢同时将一个类添加到body中,以便为您要修复的元素添加顶部填充,这样页面就不会跳动,滚动也更加平滑。$('body').addClass("FixedElementOffset"); - Nickfmc

9
如果浏览器支持“position:fixed”,则下面的纯JavaScript示例更快:
<html>
<head>
<style>
html,body {
  margin: 0;
}
#navbar.navbar_fixed {
  position:fixed;
  top:0px;
  width:100%;
  height:100px;
  background-color:#f00;
}
#navbar.navbar_absolute {
  position:absolute;
  top:100px;
  width:100%;
  height:100px;
  background-color:#f00;
}
</style>
<script type="text/javascript">

function window_onload() {
  window.addEventListener("scroll",navbar_reset_top,false);
}

var navbar_top=100;

function navbar_reset_top() {
  var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
  if(scrollTop>navbar_top&&navbar.className==="navbar_absolute") {
    document.getElementById("navbar").className="navbar_fixed";
  }
  else if(scrollTop<navbar_top&&navbar.className==="navbar_fixed") {
    document.getElementById("navbar").className="navbar_absolute";
  }
}

</script>
</head>
<body onload="javascript:window_onload();">
<div id="navbar" class="navbar_absolute">Navigation Bar</div>
<div style="height:2000px;background-color:#ff0;">Content</div>
</body>
</html>

这是一个更好的解决方案,因为它消除了另一个建议上的闪烁,该建议在每次滚动时不断重新定位。 - Jeff Putz

5

使用:

#element {
  position: fixed;
  right: 200px;
  top: 200px;
}

“fixed”表示该元素与浏览器窗口的位置有关。

1
通过将div的位置设置为position:fixed

0

使用CSS和原生JavaScript解决方案(不使用jQuery):

CSS:用于实现固定顶部定位。

.sticky {
    position: fixed;
    top: 0;
    width: 100%;
}

JavaScript:根据用户滚动位置动态添加/删除CSS类(.sticky)。
const g_fixedNavbar = document.getElementById("fixed-navbar-Id");

// Sticky Nav bar
window.onscroll = function () {
    if (window.pageYOffset > g_fixedNavbar.offsetTop) {
        g_fixedNavbar.classList.add("sticky");
    } else {
        g_fixedNavbar.classList.remove("sticky");
    }
};

以下是示例工作代码:

const g_fixedNavbar = document.getElementById("fixed-navbar-Id");

    // Sticky Nav bar
    window.onscroll = function () {
        if (window.pageYOffset > g_fixedNavbar.offsetTop) {
            g_fixedNavbar.classList.add("sticky");
        } else {
            g_fixedNavbar.classList.remove("sticky");
        }
    };
    /* Must */
    .sticky {
        position: fixed;
        top: 0;
        width: 100%;
    }

    /* Cosmetic */
    #fixed-navbar-Id {
       width: 100%;
       background: red;
    }
<h1> Some Header </h1>
    <div id="fixed-navbar-Id">Nav Controls</div>
    <h3>
        some content <br>some content <br>some content <br>some content <br>
        some content <br>some content <br>some content <br>some content <br>
        some content <br>some content <br>some content <br>some content <br>
        some content <br>some content <br>some content <br>some content <br>
    </h3>


0

与其定义滚动长度,为什么我们不能定义对象的位置呢?比如说一旦它到达顶部:0,就触发脚本。这样会更加设备友好。


我觉得这个回答并没有真正解答问题。他并没有问关于“定义滚动长度”(不知道是什么意思?),他问的是如何实现固定页眉。 - dmeglio

0
你可以像这样做:

示例

css

body {
    height: 3000px;
    top: 0;

}
#image {
    width: 100%;
    background: #444;
    height: 50px;
}
#scroller{
    height:100px;
    background:#ccc;
}
.stuck{
    position:fixed;
    z-index:100;
    width:100%;
    top:0;
}

脚本

$(window).scroll(function() {
                if ($(window).scrollTop() > 50) {
                    $('#scroller').addClass('stuck');
                } else {
                    $('#scroller').removeClass('stuck');
                }

            });

滚动50像素后,它将更改滚动条的CSS。

这可能是一个不错的开始。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接