当它到达窗口顶部时如何使div粘到顶部

时间:2015-06-26 21:13:40

标签: javascript html css

当页面的滚动位置到达顶部时,如何使#headnav粘到顶部,然后在它返回到原始位置时解开?

P.S。代码中重复的“内容”是模拟滚动。它不是垃圾邮件

jsFiddle

<h1>I AM A HEADER</h1>
<div id="headnav"></div>
<pre><h1>
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
    CONTENT
</h1></pre>
body {
    margin:0
}

#headnav {
    height: 75px;
    width: 100%;
    background-color: black;
}

4 个答案:

答案 0 :(得分:2)

这是一件非常简单的事情。

找出标题的原始位置,然后将一个滚动处理程序附加到主体,该主体检查滚动位置与div的原始位置。

  • 如果滚动位置大于原始位置,请添加grails-app/conf
  • 如果滚动位置小于原始位置,请删除position: fixed

Demo

position: fixed

答案 1 :(得分:0)

只需将position: fixed提交给h1

h1 {position: fixed; top: 0;}

小提琴:http://jsfiddle.net/5z4paLgr/1/

答案 2 :(得分:0)

我不确定是否正确理解你,但可能对你有帮助

小提琴http://jsfiddle.net/jg4kdfqs/1/

<强>的JavaScript

$(document).ready(function(){
  var HeaderTop = $('#header').offset().top;
  var hh =HeaderTop + 300;

  $(window).scroll(function(){
    if( $(window).scrollTop() > HeaderTop ) {
      if($(window).scrollTop() > hh) {
        $('#header').css({position: 'fixed', top: '0px', background:'#000'});   
      } else{
        $('#header').css({position: 'fixed', top: '0px'});  
      }


    } else {
      $('#header').css({position: 'static',background:'red'});
    }
  });
});

<强> HTML

<div id="header">
  nav
</div> 

答案 3 :(得分:0)

与tarasikgoga类似,但纯粹是javascript:

小提琴 http://jsfiddle.net/5z4paLgr/3/

<强>的Javascript

var attached = false;

window.onscroll = function (e) {
    if(!attached && window.scrollY > 150){
        attached = true;
        document.getElementById("headnav").classList.add('fixed-top');
        document.getElementById("content").classList.add('content-margin-top');
    }
    if(attached && window.scrollY < 150){
        attached = false;
        document.getElementById("headnav").classList.remove('fixed-top');
        document.getElementById("content").classList.remove('content-margin-top');
    }
} 

<强> CSS

body {
    margin:0
}
h1{
    height: 150px;
    margin: 0;
}
#headnav {
    height: 75px;
    width: 100%;
    background-color: black;
}
#headnav.fixed-top{
    position: fixed;
    top: 0;
}
.content-margin-top{
    margin-top: 75px;
}

<强> HTML 只需添加id =&#34;内容&#34;到您的内容div

使用您的高度进行调整(此处标题为150px,菜单为75px)