【问题标题】:Bind vertical scroll position to counter将垂直滚动位置绑定到计​​数器
【发布时间】:2016-06-01 19:34:53
【问题描述】:

我猜这很容易,但我是 jQuery 新手,所以我有点迷茫。

动画相对于用户垂直滚动位置上升的数字的最佳方式是什么?我正在制作一百万像素长的 div,并且想要一个从 0 到一百万的固定数字。我是否正确地说我必须使用 .scrollTop() 函数?

为高级的任何帮助干杯!

B

【问题讨论】:

  • 一百万像素 - 严重吗?那么某种缩放呢?
  • @axel.michel - 我正在制作一个使用单个像素来说明比例的信息图。

标签: javascript jquery css scrolltop


【解决方案1】:

以下代码应该可以帮助您入门。如果将 html 标记的高度增加到 100 万像素,您将拥有一个具有所需范围的计数器。

源代码来自this page。我刚刚从中创建了jsFiddle

$(function() {
    // move the counter with page scroll
    // source from this page http://www.pixelbind.com/make-a-div-stick-when-you-scroll/
    var s = $("#counter");
    var pos = s.position();                   
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        s.html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
        
        if (windowpos >= pos.top) {
            s.addClass("stick");
        } else {
            s.removeClass("stick");
        }
    });
    
});
html {
    /*force to show vert. scrollbar*/
    overflow-y: scroll;
    height: 1000200px;
    background: url("http://placehold.it/1000x500");
}
div#counter {
    padding:20px;
    margin:20px 0;
    background:#AAA;
    width:190px;
}
.stick {
    position:fixed;
    top:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Dummy text. just to show distance from top calculation.<br/><br/><br/><br/></p>
<div id="counter"></div>

【讨论】:

    猜你喜欢
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多