如何在Javascript中确定用户使用鼠标滚轮开始滚动时会滚动多少像素?

3
如何在JavaScript中确定用户使用鼠标滚轮开始滚动时,垂直滚动条将移动多少像素。
我有这样一个情况,用户的滚动将导致offsetTop之间的变化从200px到1000px,我想提前知道这种情况,我们是否有办法使用JavaScript来解决?

1
你能分享一下那段代码吗? - Sandrin Joy
据我所知,这是不可能完成的。实际上,控制向下滚动的设置都包含在鼠标中。这也就是为什么这可能因型号和其设置而异的原因。 - Giuppox
@Sandrin Joy,我需要在鼠标滚轮事件后滚动条停止的像素位置。 - Dip Parmar
你只是想找到身体的高度吗? - Sandrin Joy
1
也许如果您分享为什么需要那个信息,我们可以提供帮助。 - Joshua
显示剩余22条评论
5个回答

1
如果我正确理解了您的问题,简短的答案是“不行”。为了说明这一点,请考虑以下等效的问题:
我在down箭头上检测到一个keydown事件。我能预测用户何时释放down键吗?
这是不可能的。释放按键的时间由用户决定,您无法预测何时释放。
对于特定的鼠标滚轮事件,您还需要考虑硬件/鼠标和软件/浏览器的差异,这将使(已经不可能的?)任务更加困难。
另一种方法:防抖动您的鼠标滚轮事件
如果没有更多关于您整体目标的信息,很难知道这是否有所帮助,但您可以使用防抖函数在一段时间内规范化鼠标滚轮事件。因此,无论用户滚动0.5秒还是1秒,您只会收到一个事件,这应该简化您需要做的任何计算。

这里有一个基本的Javascript Stackblitz示例,将鼠标滚轮事件防抖到每0.1秒。如果您进行连续的鼠标滚轮滚动,则只会发出第一个事件。

RxJS内置了debounceTime函数。我不太熟悉React,无法确切地指导如何将其应用于鼠标事件,但原理与上面的示例相同。


我理解您的观点,但是假设用户只滚动鼠标滚轮一次,那么有没有办法获取该值,就像您提到按键(向下箭头)一样,假设用户只按一次键,那么我们能否获取滚动条从开始位置停止的像素值(在浏览器内部滚动过程结束之前)? - Dip Parmar
1
理论上,如果你能在“一个”鼠标滚轮事件之前和之后获取屏幕的垂直位置,那么你可以将它们相减,但是在鼠标滚轮被使用之前你不会知道这一点。实际上,我认为即使你能够获得一个值,由于硬件、软件和用户行为的差异,它也会非常不可靠,因此我认为你最好考虑其他解决方案。 - Matt Saunders
是的,我已经尝试过了,但似乎不可行,因为它至少需要事件发生一次。 - Dip Parmar

0

我看了一下你的评论“我正在尝试将位于iframe内部的页脚固定,但它应该根据父窗口滚动来调整其位置。” 根据你的要求,我尝试做了些东西。

请在全屏模式下查看

var block=document.getElementById('div');
    
window.addEventListener('scroll',function(){
var scrolled=window.scrollY;
   
if(scrolled>=471 && scrolled<=963){
    block.style.overflowY="scroll";
    
    
    if(block.scrollTop>=519){
        block.style.overflowY="hidden";
    
    }
    else if(block.scrollTop>=0){
        
    block.scrollTop+=(scrolled-519);
    window.scrollTo(0,scrolled);
    
}


}
else{
    if(scrolled<=741){
    block.style.overflowY="scroll";
   
    block.scrollTop=0;
    if(block.scrollTop<=0){
        block.style.overflowY="hidden";
    }
}

    window.scrollTo(0,scrolled);
}
});
*{
            margin: 0px;
            padding:0px;
        
        }
        body{
            height:2400px;
        }
        p{
            font-size: 20px;
        }
        #div{
           position: absolute;
           scroll-behavior: smooth;
           height:401px; 
           width: 97vw;
           margin-top:570px;
           background-color:black;
           color: white; 
           padding:10px;
           z-index: 14;
        }
        #div::-webkit-scrollbar {
  display: none;
}
        #p_3{
            position: absolute;
            margin-top:940px;
            background-color: white;
            color: black;
            z-index: 11;
            width: 100vw;
            padding: 10px;
            
        }
        #p_1{
            position: absolute;
            background-color: white;
            color: black;
            z-index: 11;
            width: 100vw;
            padding: 10px;
            
        }
<div id="p_1">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
<div id="div">
    <div id="p">
    <p >1 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color:red; color:white">2 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: #FF5733; color:white">3 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color:#FCB607; color:white">4 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color:#FCDB07 ; color:white">5 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: yellow; color:white">6 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: #07D7FC; color:white">7 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: #07B2FC; color:white">8 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: #0755FC; color:white">9 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: black; color:white">10 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

</div>
</div>
<br>
<br>
<br>
<div id="p_3">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p >Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p >Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

但是如果你仍然想坚持使用mouseWheel,那么你应该采用IntersectionObserver来实现。

“Intersection Observer”提供了异步观察元素相交(重叠)变化的方式。这可以与其他元素或视口相关。


0
我明白你想要在滚动事件开始时获取即将被滚动的像素。
但这不仅仅是一个网页/代码问题。滚动会一直持续到用户感觉停止为止。
这还取决于鼠标滚轮硬件。有些鼠标有硬滚轮,当我们松开手指时精确停止,而其他鼠标则有软齿轮,继续滚动一段时间(牛顿运动定律)。
网站开发人员无法控制这些硬件未来的表现(预测性能),例如用户何时从特定键上松开手指或何时释放鼠标按钮等。
我们唯一得到的是硬件已完成/正在进行的性能(已完成任务/当前任务),例如keyup、keydown、click、scrolling。
这些事件返回的是当前正在发生的事情以及之前发生的事情。

预测用户滚动持续时间的唯一方法是通过机器学习,了解用户通常如何滚动,了解他们使用的滚动设备等等。

但是我们为什么需要它呢?我能想到的用例是用于理解用户的滚动行为的机器学习模型。

我有一个情况,用户的滚动将导致offsetTop在200px到1000px之间变化,我想提前知道,我们是否有办法使用javascript解决这种情况?

对于这种特定情况,没有必要在停止之前获取滚动像素。基本的滚动事件就足够了。

也许您想在达到1000px之前进行小型动画,这可以直接使用CSS和JavaScript通过在滚动上创建事件侦听器来完成(如果当前offsetTop == 1000px,则...)

这是一个代码片段,告诉您用户在滚动事件中滚动了多少像素(已完成任务)

const ph=document.documentElement.scrollHeight;
console.log(ph)
document.querySelector('.rem').innerHTML="you have scrolled "+window.pageYOffset+". Scroll ends after "+((ph-window.innerHeight)-window.pageYOffset);
document.onscroll = () =>{
if(window.pageYOffset>1000){
 var cl=document.getElementById("gm");
 cl.classList.add("wow");
}
if(window.pageYOffset<1000){
 var cl=document.getElementById("gm");
 cl.classList.remove("wow");
}
document.querySelector('.rem').innerHTML="you have scrolled "+window.pageYOffset+". Scroll ends after "+((ph-window.innerHeight)-window.pageYOffset);
};
.rem{
position:fixed;
top:0;
}
.demo{
height:5000px;
}

.wow{
background:#FFCB2B;
transition:2s;
}
<span class="rem" id="xy"></span>
<div class="demo" id="gm">
<div>

好的,我将创建一个简单的机器学习JS片段来研究用户的滚动行为,以便针对此滚动事件进行处理。

目前我只是针对单向滚动进行训练。因此,每次滚动都会进行上滚或下滚。

前10次滚动仅用于学习。之后,当您开始滚动事件时,它将使用已学习的值预测即将到来的滚动值。

该模型将持续学习,不会在前10次尝试学习后停止。学习值越高,获得的预测值就越真实。

const ph=document.documentElement.scrollHeight;
const sp=[];
var prevscroll=0;
var curscroll=0;
learn=0;
var scrollTimer = -1;
console.log(ph)
document.querySelector('.rem').innerHTML="you have scrolled "+window.pageYOffset+". Scroll ends after "+((ph-window.innerHeight)-window.pageYOffset);

document.onscroll = () =>{

if (scrollTimer != -1)
       clearTimeout(scrollTimer);
  scrollTimer = window.setTimeout("scrollFinished()", 300);
if(learn>=10){
var c=avgscroll()
document.querySelector('.rem').innerHTML="your expected scroll pixels are "+c;
}

};
function avgscroll(){
  curavg=0
sp.forEach((item, index)=>{
      if(index!=0)
        curavg=(curavg+item)/(2)
       else
          curavg=item
});
return curavg;
}
function scrollFinished() {
        learn=learn+1;
        curpoint=window.pageYOffset
        curscroll=Math.abs(window.pageYOffset-prevscroll);
        prevscroll=curpoint;
        sp[learn]=curscroll
        console.log("Current Scroll was "+ curscroll)
        if(learn<=10)
        document.querySelector('.rem').innerHTML="Current Scrolled pixels were "+curscroll+" learning "+ learn + " of 10";
        
    }
.rem{
position:fixed;
top:0;
}
.demo{
height:50000px;
}
<span class="rem" id="xy"></span>
<div class="demo">
<div>


0

@Dip Parmar,我在一个名为useDocumentScroll.js的文件中给你提供了先前滚动位置和当前滚动位置。先前滚动是您正在查找的一个滚动的终点。我使用React函数钩子完成了它。您可以根据需要在RequiredPage.js中放置自己的逻辑来相应地使用它们。我还为您包含了一些逻辑.. isScrolledDown和isMinimumScrolled。我无法确切地理解您想要使用它做什么。我的代码如下:

useDocumentScroll.js

import { useEffect, useState } from "react";


function useDocumentScroll(callback) {
  const [, setScrollPosition] = useState(0);
  let previousScrollTop = 0;

  function handleDocumentScroll() {
    const { scrollTop: currentScrollTop } =
      document.documentElement || document.body;

    setScrollPosition(previousPosition => {
      previousScrollTop = previousPosition;
      return currentScrollTop;
    });

    callback({ previousScrollTop, currentScrollTop });
  }

   useEffect(() => {
    window.addEventListener("scroll", handleDocumentScroll);

    return () =>
      window.removeEventListener("scroll", handleDocumentScroll);// eslint-disable-next-line
  }, []);
}

export default useDocumentScroll;

RequiredPage.js

import React from "react";    
import useDocumentScroll from "./useDocumentScroll";

export default function RequiredPage() {
const MINIMUM_SCROLL = 80;

useDocumentScroll(callbackData => {
const { previousScrollTop, currentScrollTop } = callbackData;
const isScrolledDown = previousScrollTop < currentScrollTop;
const isMinimumScrolled = currentScrollTop > MINIMUM_SCROLL;
});

return (
     <div>
     <h1>Some Text or Add some Lorem Ipsum </h1>
     </div>
       );
    }

-1

从您的查询中我猜测您想要这种解决方案

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body style="height:900px;background-color:limegreen;">
  
</body>
</html>


1
不,我想在第一次处理程序执行时获取关于像素结束位置的信息。(仅针对一次鼠标滚轮移动) - Dip Parmar
如何在JavaScript中确定用户使用鼠标滚轮开始滚动时将滚动多少像素。 - Radiant Ahmed
1
这就是为什么我提到了它将会移动多少,而不是它已经移动了。 - Dip Parmar
1
人类自问自己,是为了未来的位置而不是我们现在所处的位置。 - Dip Parmar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接