使元素固定在滚动上

时间:2013-03-18 18:22:23

标签: javascript jquery html css

我试图让导航栏粘到顶部,当用户向下滚动到导航栏然后在用户向上滚动通过导航栏时解开。我知道这只能通过JavaScript实现。我是JavaScript的初学者,所以越容易越好。 The JSFIDDLE is here.

HTML如下:

   <section class="main">
     <div id="wrap">
        <div id="featured">
     <div class="wrap">      
  <div class="textwidget">
    <div class="cup"><img src="#""></div>
<div id="header"></div></div></div></div></div></div></div>
<div class="whiteboard">
         <h1><a href="#">HELLO GUYS</a></h1> </div>
   </div>
          <div class="bg1">
            <h2> WE ARE AN EVENTS MANAGEMENT COMPANY BASED IN LONDON. </h2></div>

CSS如下:

      .main{text-align:center;}

      h1{
          -webkit-font-smoothing: antialiased;
              display:inline-block;
            font: 800 1.313em "proxima-nova",sans-serif; 
            padding: 10px 10px;
            margin: 20px 20px;
            letter-spacing: 8px;
            text-transform: uppercase;
              font-size:3.125em;
              text-align: center; 
              max-width: 606px;
      line-height: 1.45em;
      position: scroll;
          background-color:#e94f78;
          text-decoration: none;
          color:yellow;
          background-image:url;
      }

      h1 a{
        text-decoration: none;
        color:yellow;
                padding-left: 0.15em;
      }

      h2{
          -webkit-font-smoothing: antialiased;
              display:inline-block;
            font: 800 1.313em "proxima-nova",sans-serif; 
            letter-spacing: 8px;
            margin-top: 100px;
            text-transform: uppercase;
              font-size:3.125em;
              text-align: center; 
      line-height: 1.45em;
      position: scroll;
          text-decoration: none;
          color:white;
          z-index: -9999;
      }

      h2 a{
        text-decoration: none;
        color:white;
                padding-left: 0.15em;
      }

      h5{

      position: absolute;
              font-family:sans-serif; 
              font-weight:bold; 
              font-size:40px; 
              text-align: center; 
              float: right;
              background-color:#fff;
              margin-top: -80px;
              margin-left: 280px;
      }

      h5 a{

        text-decoration: none;
        color:red;
      }

      h5 a:hover{

        color:yellow;
      }

      #text1{
          -webkit-font-smoothing: antialiased;
              display:inline-block;
            font: 800 1.313em "proxima-nova",sans-serif; 
            margin: 20px 20px;
            letter-spacing: 8px;
            text-transform: uppercase;
              font-size:3.125em;
              text-align: center; 
              max-width: 606px;
      line-height: 1.45em;
      position: scroll;
          background-color:#E94F78;

      }

      #text1 a{
          color:yellow;
          text-decoration: none;
              padding-left: 0.15em;


      }

      #text1 a:hover{

          text-decoration: none;
          cursor:pointer;
      }

      .whiteboard{
          background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
          background-position: center;
          padding: ;
          background-color: #fff;
          z-index: 1000;
      }

      .bg{
        height:2000px;
        background-color:#ff0;
        background-image:url(http://alwayscreative.net/images/stars-last.jpg);
        position:relative;
        z-index: -9999;

      }
      .bg1{
        background-image:url(http://alwayscreative.net/images/stars-last.jpg);
        z-index: -9999;
        height:1000px;
      }
      /* Header */
      #wrap {
        margin: 0 auto;
        padding: 0;
        width: 100%;
      }

      #featured {
        background: #E94F78 url(http://www.creativityfluid.com/wp-content/themes/creativityfluid/images/img-bubbles-red.png) no-repeat top;
        background-size: 385px 465px;
        color: #fff;
        height: 535px;
        overflow: hidden;
        position: relative;
        z-index: -2;
      }


      #featured .wrap {
        overflow: hidden;
        clear: both;
        padding: 70px 0 30px;
        position: fixed;
        z-index: -1;
        width: 100%;
      }


      #featured .wrap .widget {
        width: 80%;
        max-width: 1040px;
        margin: 0 auto;
      }

      #featured h1,
      #featured h3,
      #featured p {
        color: yellow;
        text-shadow: none;
      }

      #featured h4{
        color:white;
        text-shadow:none;
      }

      #featured h4 {
        margin: 0 0 30px;
      }

      #featured h3 {
        font-family: 'proxima-nova-sc-osf', arial, serif;
        font-weight: 600;
        letter-spacing: 3px;
      }

      #featured h1 {
        margin: 0;
      }

      .textwidget{
        padding: 0;
      }

      .cup{
        margin-top:210px;
        z-index: 999999;
      }

      .container{font-size:14px; margin:0 auto; width:960px}
      .test_content{margin:10px 0;}
      .scroller_anchor{height:0px; margin:0; padding:0;background-image:url()}
      .scroller{background:#FFF;
        background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
       margin:0 0 10px; z-index:100; height:50px; font-size:18px; font-weight:bold; text-align:center; width:960px;}

11 个答案:

答案 0 :(得分:69)

你可以用一些简单的jQuery来做到这一点:

http://jsfiddle.net/jpXjH/6/

var elementPosition = $('#navigation').offset();

$(window).scroll(function(){
        if($(window).scrollTop() > elementPosition.top){
              $('#navigation').css('position','fixed').css('top','0');
        } else {
            $('#navigation').css('position','static');
        }    
});

答案 1 :(得分:17)

我不打扰jQuery或LESS。在我看来,javascript框架有点过分了。

window.addEventListener('scroll', function (evt) {

  // This value is your scroll distance from the top
  var distance_from_top = document.body.scrollTop;

  // The user has scrolled to the tippy top of the page. Set appropriate style.
  if (distance_from_top === 0) {

  }

  // The user has scrolled down the page.
  if(distance_from_top > 0) {

  }

});

答案 2 :(得分:14)

实施此问题存在一些问题,原来接受的答案没有回答:

  1. 窗口的onscroll事件经常发生。这个 意味着你要么必须使用一个非常高效的监听器,要么 你必须以某种方式推迟听众。 jQuery Creator John Resig 陈述here怎么样? 可以实施延迟机制,以及你应该这样做的原因 做到这一点。在我看来,鉴于今天的浏览器和环境,a 高效的倾听者也会这样做。 Here is an implementation of the pattern suggested by John Resig
  2. 方式位置:固定在css中工作,如果向下滚动页面并将元素从position:static移动到position: fixed,页面将会跳转到#34;一点点因为文件&#34;松散&#34;元素的高度。您可以通过向scrollTop添加高度来删除它,并将文档正文中丢失的高度替换为另一个对象。您还可以使用该对象来确定粘性项是否已移至position: fixed,并减少对将position: fixed恢复为原始状态的代码的调用:Look at the fiddle here
  3. 现在,处理程序实际上在性能方面唯一昂贵的就是在每次调用时调用scrollTop。由于区间绑定处理程序也有其缺点,我在这里争辩说你可以将事件监听器重新连接到原始的滚动事件,使其感觉更加快速而不用担心。但是,您必须在您定位/支持的每个浏览器上对其进行分析。 See it working here
  4. 以下是代码:

    JS

    /* Initialize sticky outside the event listener as a cached selector.
     * Also, initialize any needed variables outside the listener for 
     * performance reasons - no variable instantiation is happening inside the listener.
     */
    var sticky = $('#sticky'),
        stickyClone,
        stickyTop = sticky.offset().top,
        scrollTop,
        scrolled = false,
        $window = $(window);
    
    /* Bind the scroll Event */
    $window.on('scroll', function (e) {
        scrollTop = $window.scrollTop();
    
        if (scrollTop >= stickyTop && !stickyClone) {
            /* Attach a clone to replace the "missing" body height */
            stickyClone = sticky.clone().prop('id', sticky.prop('id') + '-clone')
            stickyClone = stickyClone.insertBefore(sticky);
            sticky.addClass('fixed');
        } else if (scrollTop < stickyTop && stickyClone) {
            /* Since sticky is in the viewport again, we can remove the clone and the class */
            stickyClone.remove();
            stickyClone = null;
            sticky.removeClass('fixed');
        }
    });
    

    CSS

    body {
        margin: 0
    }
    .sticky {
        padding: 1em;
        background: black;
        color: white;
        width: 100%
    }
    .sticky.fixed {
        position: fixed;
        top: 0;
        left: 0;
    }
    .content {
        padding: 1em
    }
    

    HTML

    <div class="container">
      <div id="page-above" class="content">
        <h2>Some Content above sticky</h2>
        ...some long text...
      </div>
      <div id="sticky" class="sticky">This is sticky</div>
      <div id="page-content" class="content">
        <h2>Some Random Page Content</h2>...some really long text...
      </div>
    </div>
    

答案 3 :(得分:7)

在这里,没有框架,简短而简单:

var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;

window.addEventListener('scroll', function(){
    if (document.documentElement.scrollTop > elTop){
        el.style.position = 'fixed';
        el.style.top = '0px';
    }
    else
    {
        el.style.position = 'static';
        el.style.top = 'auto';
    }
});

答案 4 :(得分:5)

您想使用jQuery WayPoints。这是一个非常简单的插件,并且完全符合您的描述。

最直接的实施

    $('.thing').waypoint(function(direction) {
  alert('Top of thing hit top of viewport.');
});

您需要设置一些自定义CSS以准确设置卡住的位置,这在大多数方法中都是正常的。

This page会向您显示所需的所有示例和信息。

为了将来参考,停止和启动的示例是this website。这是一个“在野外”的例子。

答案 5 :(得分:1)

您可以访问LESS CSS网站http://lesscss.org/

他们的可停靠菜单很轻,表现也很好。唯一需要注意的是,效果在滚动完成后发生。只需查看视图来查看js。

答案 6 :(得分:1)

你也可以用css做到这一点。

只需使用position:fixed; 当你向下滚动时想要修复的内容。

你可以在这里找到一些例子:

http://davidwalsh.name/demo/css-fixed-position.php

http://demo.tutorialzine.com/2010/06/microtut-how-css-position-works/demo.html

答案 7 :(得分:1)

window.addEventListener("scroll", function(evt) {
    var pos_top = document.body.scrollTop;   
    if(pos_top == 0){
       $('#divID').css('position','fixed');
    }

    else if(pos_top > 0){
       $('#divId').css('position','static');
    }
});

答案 8 :(得分:1)

普通Javascript解决方案(DEMO):

<br/><br/><br/><br/><br/><br/><br/>
<div>
  <div id="myyy_bar" style="background:red;"> Here is window </div>
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>


<script type="text/javascript">
var myyElement = document.getElementById("myyy_bar"); 
var EnableConsoleLOGS = true;           //to check the results in Browser's Inspector(Console), whenever you are scrolling
// ==============================================



window.addEventListener('scroll', function (evt) {
    var Positionsss =  GetTopLeft ();  
    if (EnableConsoleLOGS) { console.log(Positionsss); }
    if (Positionsss.toppp  > 70)    { myyElement.style.position="relative"; myyElement.style.top = "0px";  myyElement.style.right = "auto"; }
    else                            { myyElement.style.position="fixed";    myyElement.style.top = "100px";         myyElement.style.right = "0px"; }
});



function GetOffset (object, offset) {
    if (!object) return;
    offset.x += object.offsetLeft;       offset.y += object.offsetTop;
    GetOffset (object.offsetParent, offset);
}
function GetScrolled (object, scrolled) {
    if (!object) return;
    scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
    if (object.tagName.toLowerCase () != "html") {          GetScrolled (object.parentNode, scrolled);        }
}

function GetTopLeft () {
    var offset = {x : 0, y : 0};        GetOffset (myyElement.parentNode, offset);
    var scrolled = {x : 0, y : 0};      GetScrolled (myyElement.parentNode.parentNode, scrolled);
    var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
    return {lefttt: posX , toppp: posY };
}
// ==============================================
</script>

答案 9 :(得分:0)

最简单的方法如下:

[AlsoNotifyFor(nameof(GoButtonIsEnabled ))]
public string Test { get; set; }

答案 10 :(得分:0)

最近对我有用的解决方案是:

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

var header = document.getElementById("filters-tab");
var sticky = header.offsetTop;

if (window.pageYOffset > sticky) {
  header.classList.add("fixed");
} else {
  header.classList.remove("fixed");
}