【问题标题】:How to determine how much user will scroll by pixels when user start scrolling using mouse wheel in Javascript当用户在Javascript中使用鼠标滚轮开始滚动时,如何确定用户将滚动多少像素
【发布时间】:2020-09-29 14:30:15
【问题描述】:

当用户开始在javascript中使用鼠标滚轮滚动时,如何确定垂直滚动条将移动多少像素

我有一种情况,用户的滚动会导致 offsetTop 在 200px 到 1000px 之间发生变化,我想提前知道,我们有什么方法可以使用 javascript 找出这种情况吗?

【问题讨论】:

  • 你为此做了什么?
  • @SandrinJoy 我试图通过第一次执行事件处理程序(通过滚轮移动事件)并测量滚动事件结束时 offsetTop 值差异的变化来获取信息将滚动多少页面,但我想要从一开始,就像在滚动事件执行完成之前一样。
  • 你能分享那个代码吗?
  • 请正确描述您的问题并显示您尝试过的代码
  • 也许如果您分享您想要该信息的原因,我们或许可以提供帮助。

标签: javascript html css reactjs angular


【解决方案1】:

如果我正确理解您的问题,简短的回答是“不”。为了说明这一点,请考虑以下等效问题:

我在down 箭头上检测到keydown 事件。我可以预测用户何时会释放down 键吗?

这是不可能的。何时释放密钥取决于用户,而您无法预测何时释放。

特别是关于鼠标滚轮事件,您还需要考虑硬件/鼠标和软件/浏览器的变化,这将使(已经不可能的?)任务变得更加困难。

另一种方法:消除鼠标滚轮事件的抖动

如果没有关于您的总体目标的更多信息,很难知道这是否会有所帮助,但您可以使用去抖动功能来规范一段时间内的鼠标滚轮事件。因此,无论用户滚动(例如)0.5 秒还是 1 秒,您都只会得到一个事件,这应该会简化您需要进行的任何计算。

Here is a basic Javascript Stackblitz example,每 0.1 秒去一次鼠标滚轮事件。如果您进行连续的鼠标滚轮滚动,则应该只发出第一个事件。

RxJS has a debounceTime function 内置。我对 React 不熟悉,所以我无法确切说明如何将其应用于鼠标事件,但原理与上面的示例相同。

【讨论】:

  • 我理解你的意思,但假设用户滚动鼠标滚轮一次,那么有没有办法获得该值,就像你提到的按键假设用户只按下一次键(向下箭头)然后可以我们以像素为单位获得值,滚动条将从一开始就停止(在浏览器内部滚动过程结束之前)
  • 理论上,我猜,如果你能在“一个”鼠标滚轮事件之前和之后得到屏幕的垂直位置,你可以从另一个中减去一个,但你不能在使用鼠标滚轮之前会知道这一点。实际上,我认为即使你能得到一个值,它也会非常不可靠,因为我已经提到了硬件、软件和用户行为的变化。我认为您最好考虑其他解决方案。
  • 是的,我已经尝试过了,但这似乎不可行,因为它至少需要发生一次该事件
【解决方案2】:

@Dip Parmar,我在单独的 useDocumentScroll.js 文件中提供了前一个滚动位置和当前滚动位置。上一个滚动是您正在寻找的一个滚动的终点。我已经在 React 功能挂钩中完成了它。您可以根据RequiredPage.js 中的要求通过放置您自己的逻辑来相应地使用它们。我还包含了一些逻辑.. isScrolledDown 和 isMinimumScrolled 为您服务。我不能完全得到你想用它做什么。我的问题代码如下:

使用DocumentScroll.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>
       );
    }

【讨论】:

    【解决方案3】:

    我了解到您希望在滚动事件开始时滚动像素。

    但这不仅仅是一个网络/代码问题。滚动一直持续到用户感觉停止为止。

    这也取决于鼠标滚轮硬件。有些带有硬轮的鼠标会在我们松开手指时完全停止,而其他带有软齿轮的鼠标会继续滚动运动更长的时间(牛顿运动定律)。

    Web 开发人员无法控制这些即将推出的硬件 性能(预测性能),例如用户什么时候 从特定键上松开手指或用户何时松开 鼠标按钮等...

    我们唯一得到的是硬件已完成/正在进行的性能(已完成的任务/当前),例如 keyup 、 keydown、click 、scrolling

    这些事件返回目前正在发生的事情和之前发生的事情


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

    但是我们为什么需要它呢?我可以提出的用例是一个用于理解用户滚动行为的 ML 模型

    我有一种情况,用户的滚动会导致 offsetTop 发生变化 我想提前知道的 200px 到 1000px 之间,我们有吗 有什么方法可以使用 javascript 找出这种情况?

    对于这种特殊情况,没有在滚动像素停止之前获取滚动像素的用例。一个基本的滚动事件就足够了。

    也许您希望它在达到 1000px 之前给出一个迷你动画,这可以通过在滚动上创建一个事件监听器直接使用 css 和 javascript 来完成(如果当前 offsetTop==1000px 那么 ....)

    这是一个 sn-p,它告诉您用户在滚动事件中滚动了多少像素(已完成任务)

    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 sn-p

    我现在只训练单向滚动。所以对于每个滚动,向上滚动或向下滚动

    前 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>

    【讨论】:

      【解决方案4】:

      我阅读了您的评论 '我正在尝试修复 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”提供了一种异步观察元素交集(重叠)变化的方法。这可以与其他元素或视口相关。

      【讨论】:

        【解决方案5】:

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

        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>

        【讨论】:

        • 不,我想在第一次执行处理程序时获取有关以像素为单位的结束位置的信息。 (仅一次鼠标滚轮移动)
        • “当用户在 JavaScript 中使用鼠标滚轮开始滚动时,如何确定用户将滚动多少像素”这是您的查询,这意味着我得到的连续性
        • 这就是为什么我提到它会移动多少而不是它已经移动了
        • 男人质疑自己说的是未来的位置,而不是我们现在所处的位置
        猜你喜欢
        • 1970-01-01
        • 2010-10-11
        • 1970-01-01
        • 2011-09-29
        • 2020-08-07
        • 2018-05-13
        • 2010-12-08
        • 2011-01-12
        • 1970-01-01
        相关资源
        最近更新 更多