简体   繁体   English

如何使用Jquery检测滚动速度?

[英]How to detect scroll speed with Jquery?

I would like to try and replicate io7's safari feature, where the url and navigation bars minimize when you scroll slowly, in javascript/jquery. 我想尝试复制io7的safari功能,在javascript / jquery中,当你慢慢滚动时,url和导航栏最小化。 The first thing is to detect scroll speed, I have seen this question already, but I am doing this in a content script so I don't necessarily have the top and bottom element that they use. 首先要检测滚动速度,我已经看过这个问题,但我在内容脚本中这样做,所以我不一定要使用它们使用的顶部和底部元素。 Is there another way to detect scroll speed? 还有另一种检测滚动速度的方法吗?

You could attach to the scroll event via jQuery and use a combination of timestamps and the scrollOffset to determine scroll speed by comparing the offset/time to the last scroll event before. 您可以通过jQuery附加到滚动事件,并使用时间戳和scrollOffset的组合,通过比较之前的最后一个滚动事件的偏移/时间来确定滚动速度。 Something like this: 像这样的东西:

var lastOffset = $( mySelector ).scrollTop();
var lastDate = new Date().getTime();

$( mySelector ).scroll(function(e) {
    var delayInMs = e.timeStamp - lastDate;
    var offset = e.target.scrollTop - lastOffset;
    var speedInpxPerMs = offset / delayInMs;
    console.log(speedInpxPerMs);

    lastDate = e.timeStamp;
    lastOffset = e.target.scrollTop;
});

Anyways since you don't have control over navigation bar in a regular browsers I don't see the point here :/ 无论如何,因为你没有在常规浏览器中控制导航栏我在这里没有看到这一点:/

May be you are searching for something like this: Parallax scroll with sticky header 也许你正在寻找这样的东西: 视差滚动与粘性标题

GL Chris GL克里斯

I tried to use cschuff s answer but something was wrong. 我尝试使用cschuff的答案,但出了点问题。 With this problem and the joy to write a class, I just put the code in a small class, get it here: https://github.com/SocialbitGmbH/JavascriptScrollSpeedMonitor 有了这个问题和写一个类的乐趣,我只是把代码放在一个小类中,在这里得到它: https//github.com/SocialbitGmbH/JavascriptScrollSpeedMonitor

Usage is simple: 用法很简单:

var scrollSpeedMonitor = new ScrollSpeedMonitor(function (speedInPxPerMs, timeStamp, newDirection)
{
    console.log('Scroll speed: ' + speedInPxPerMs);
});

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

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