简体   繁体   English

滚动时将Div置于页面顶部

[英]Make Div “catch” top of page when scrolling

I have a header on a website that is fixed 20px from the top of the page. 我在距页面顶部fixed 20px的网站上有一个标头。

However, I want this to catch the top of the page when scrolling and become fixed to the top of the screen once the user has scrolled that 20px down. 但是,我希望它在滚动时能抓住页面的顶部,并在用户向下滚动20px时固定在屏幕顶部。

CSS 的CSS

#header{
    padding: 0px 0px 0px 0px;
    background: url(../images/header-fill2.jpg) repeat-x top;
    position: fixed;
    height: 60px;
    width: 100%;
    top: 20px;
    z-index: 5000;
}

I imagine some form of JavaScript is required but have little to no JavaScript experience, so any help would be greatly appreciated. 我想象需要某种形式的JavaScript,但几乎没有JavaScript经验,因此,我们将不胜感激。

Just listen for the scroll event and read the value of $(window).scrollTop() and set the top according to that. 只需侦听scroll事件并读取$(window).scrollTop()的值,然后根据该值设置top
Something like: 就像是:

$(window).on('scroll', function() {
    $('#header').css('top', $(window).scrollTop() > 20 ? '0px' : '20px');
});

Example on jsFiddle jsFiddle上的示例

The scroll event tells you when the window scrolls. scroll事件告诉您窗口何时滚动。 Then, use the scrollTop to find out how much closer to 0 to go: 然后,使用scrollTop找出离0更近的距离:

$(window).on("scroll", function() {
  $("#header").css("top", Math.max(0, 20 - $(window).scrollTop()));
});

Live Example 现场例子

Or to avoid constantly re-creating objects: 或避免不断重新创建对象:

(function() {
  var $wnd = $(window),
      $header = $("#header");
  $wnd.on("scroll", function() {
    $header.css("top", Math.max(0, 20 - $wnd.scrollTop()));
  });
})();

Live Example 现场例子

Thats how I do that with jQuery. 那就是我用jQuery做到的方式。 The position is also cached, for performance reasons: 由于性能原因,该位置也被缓存:

Here is a fiddle: 这是一个小提琴:

http://jsfiddle.net/StephanWagner/u3yrS/ http://jsfiddle.net/StephanWagner/u3yrS/

$(document).ready(function() {

    var cfixed_nav = false, wscroll;

    var setScroll = function() {
        wscroll = $(window).scrollTop();

        var fixed_nav = wscroll > 20; // Set pixel amount here

        if (fixed_nav != cfixed_nav) {
            $('body')[fixed_nav ? 'addClass' : 'removeClass']('fixed');
            cfixed_nav = fixed_nav;
        }
    };

    setScroll();
    $(document).scroll(setScroll);
});

With CSS you set the fixed position: 使用CSS可以设置固定位置:

.fixed #header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    width: 100%
}

Also remember, that when the header gets the fixed position, those 20px of the header are missing. 还请记住,当标头到达固定位置时,标头的那些20px会丢失。 So you can add a body padding for example: 因此,您可以添加一个正文填充,例如:

.fixed {
    padding-top: 20px;
}

Or you add an element with 20 Pixel height and swap display none / block depending on the .fixed class in the body 或者添加一个像素高度为20的元素,并根据正文中的.fixed类交换无显示/块显示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM