简体   繁体   English

粘滞div平滑滚动

[英]Smooth scrolling with sticky div

I want to create a sticky div as smooth as in this example: http://www.nytimes.com/interactive/2010/11/13/weekinreview/deficits-graphic.html?src=tp&_r=0 我想创建一个像本例一样平滑的粘性div: http ://www.nytimes.com/interactive/2010/11/13/weekinreview/deficits-graphic.html?src=tp&_r =0

Right now, my example isnt smooth at all, but really jumpy. 现在,我的例子一点都不顺利,但确实令人震惊。 I have this JS-code: 我有这个JS代码:

$(window).scroll(function () {

        var scroll_top = $(this).scrollTop();
           if (scroll_top > 66) {//height of header
             $('.wrapper').addClass('sticky');
          } else {
          $('.wrapper').removeClass('sticky');
          }
   });

And the HTML: 和HTML:

<div class="wrapper">
     <h4>Ausgaben in Millionen Franken</h4>
     <div class="background">
          <div id="kunstmuseum"></div><div id="historisch"></div><div id="naturhist"></div><div id="kulturen"></div><div id="antik"></div><div id="beyeler"></div><div id="weitereMuseen"></div><div id="theaterBasel"></div><div id="kaserne"></div><div id="weitereTheater"></div><div id="sinfonie"></div><div id="jazz"></div><div id="rock"></div><div id="literatur"></div><div id="erbe"></div><div id="wettbewerb"></div><div id="weiteres"></div><div id="zoo"></div>
    </div>
    <div id="eins">0</div>
    <div id="zwei">30</div>
    <div id="drei">60</div>
    <div id="vier">90</div>
    <div id="fuenf">120</div>
    <div id="eingespart"><h4>Total eingespart:&ensp;<div id="totalSum">0&ensp;CHF</div></h4></div>
</div>

Here is the jsfiddle: http://jsfiddle.net/w640ftLf/3/ 这是jsfiddle: http : //jsfiddle.net/w640ftLf/3/

It looks like you're attaching the sticky class to the wrong element. 好像您是在将sticky类附加到错误的元素上。 Try this, instead: 试试这个,代替:

$(window).scroll(function () {
    var scroll_top = $(document).scrollTop();
    if (scroll_top > 66) {//height of header
        $('.background').addClass('sticky');
     } else {
        $('.background').removeClass('sticky');
     }
});

Also, for education, you can take a look at how your example is doing it . 另外,对于教育,您可以看一下您的榜样是如何做到的

It's not really how I would do it, but your function works fine. 这不是我真正要做的,但是您的功能可以正常工作。

The easiest way to fix your problem is to add padding-top: 66px; 解决问题的最简单方法是添加padding-top: 66px; (66 being the header height) to the body element at the same time you add the class 'sticky'. (66为标题高度)同时添加到类'sticky'到body元素。

Let me know if this works for you. 让我知道这是否适合您。

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

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