将垂直滚动位置绑定到计​​数器 [英] Bind vertical scroll position to counter

查看:64
本文介绍了将垂直滚动位置绑定到计​​数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我猜这真的很容易,但是我是jQuery的新手,所以我有点迷路了.

I'm guessing this is really easy but I'm new to jQuery so I'm a little lost.

使数字相对于用户垂直滚动位置进行动画处理的最佳方法是什么?我将div的长度设置为一百万像素,并希望使用一个固定的数字,其范围为0到一百万.我说对了,我必须使用.scrollTop()函数吗?

What’s the best way to animate a number going up relative to a users vertical scroll position? I’m making a div a million pixels long and want a fixed number that counts from 0 to a million. Am I right in saying I'd have to use the .scrollTop() function?

为高级帮助加油!

B

推荐答案

以下代码应帮助您入门.如果您将html标签的高度增加到100万像素,则会得到一个具有所需范围的计数器.

The following code should help you to get started. If you increase the height of the html tag to 1 million pixel, you'll have a counter with the desired range.

源代码来自此页面 .我刚刚从中创建了 jsFiddle .

The source code is from this page. I have just created the jsFiddle from it.

$(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>

这篇关于将垂直滚动位置绑定到计​​数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆