使元素固定在滚动上

Kad*_*rie 28 html javascript css jquery

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

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>
Run Code Online (Sandbox Code Playgroud)

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;}
Run Code Online (Sandbox Code Playgroud)

tsc*_*ela 73

你可以用一些简单的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');
        }    
});
Run Code Online (Sandbox Code Playgroud)

  • 注意IE和iPad上的性能问题 (2认同)

Sha*_*ery 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) {

  }

});
Run Code Online (Sandbox Code Playgroud)

  • "问题不在于浏览器的兼容性." (9认同)
  • 但要拥有广泛的浏览器兼容性,您还必须使用attachEvent. (4认同)
  • 问题不在于浏览器兼容性.我试图让它保持相关性和易于理解. (3认同)

Bea*_*rtz 14

实现这一点有一些问题,原来接受的答案没有回答:

  1. onscroll窗口的事件经常发生.这意味着您要么必须使用性能非常高的监听器,要么必须以某种方式延迟监听器.jQuery Creator John Resig 在这里说明了如何实现延迟机制,以及为什么要这样做.在我看来,考虑到今天的浏览器和环境,高性能的听众也会这样做.这是John Resig建议的模式的实现
  2. 方式位置:固定在css中工作,如果向下滚动页面并从位置移动元素:静态到position: fixed,页面将"跳"一点,因为文档"失去"元素的高度.您可以通过添加高度来摆脱它,并scrollTop用另一个对象替换文档正文中丢失的高度.您还可以使用该对象来确定粘性项是否已被移动到position: fixed并减少对恢复position: fixed到原始状态的代码的调用:在这里查看小提琴
  3. 现在,处理程序实际上在性能方面唯一昂贵的就是调用scrollTop每个调用.由于区间绑定处理程序也有它的缺点,我会在这里争论你可以将事件监听器重新连接到原始的滚动事件,让它感觉更快,没有太多的担忧.您必须在您定位/支持的每个浏览器上对其进行分析.看到它在这里工作

这是代码:

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');
    }
});
Run Code Online (Sandbox Code Playgroud)

CSS

body {
    margin: 0
}
.sticky {
    padding: 1em;
    background: black;
    color: white;
    width: 100%
}
.sticky.fixed {
    position: fixed;
    top: 0;
    left: 0;
}
.content {
    padding: 1em
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)


Ale*_*xTR 8

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

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';
    }
});
Run Code Online (Sandbox Code Playgroud)


tim*_*ker 5

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

最直接的实现

    $('.thing').waypoint(function(direction) {
  alert('Top of thing hit top of viewport.');
});
Run Code Online (Sandbox Code Playgroud)

您将需要设置一些自定义CSS以准确设置卡住的位置,这对于大多数方法来说都是正常的.

此页面将显示您需要的所有示例和信息.

为了将来的参考,它停止和启动的一个例子是这个网站.这是一个"野外"的例子.