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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21660348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:24:51  来源:igfitidea点击:

How to detect scroll speed with Jquery?

javascriptjquerygoogle-chrome-extension

提问by EasilyBaffled

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. The first thing is to detect scroll speed, I have seen thisquestion 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?

我想尝试复制 io7 的 safari 功能,在 javascript/jquery 中,当您缓慢滚动时,url 和导航栏会最小化。第一件事是检测滚动速度,我已经看到了这个问题,但我在内容脚本中这样做,所以我不一定有他们使用的顶部和底部元素。还有另一种方法来检测滚动速度吗?

回答by cschuff

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. Something like this:

您可以通过 jQuery 附加到滚动事件,并使用时间戳和 scrollOffset 的组合通过将偏移/时间与之前的最后一个滚动事件进行比较来确定滚动速度。像这样的东西:

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克里斯

回答by Thomas Kekeisen

I tried to use cschuffs answer but something was wrong. 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

我尝试使用cschuffs 答案,但出了点问题。带着这个问题和写一个类的乐趣,我只是把代码放在一个小类中,在这里获取:https: //github.com/SocialbitGmbH/JavascriptScrollSpeedMonitor

Usage is simple:

用法很简单:

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