javascript 如何指定每一步滚动移动多少像素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18564561/
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 12:24:51  来源:igfitidea点击:

How to specify how many pixels scroll moves on each step?

javascriptjqueryhtmlscroll

提问by skmasq

When I use mouse wheel to scroll content in divI want it to scroll by e.g., 30pxeach step or each mouse wheel tick w/e is the best solution.
I would prefer performance > easei.e. I'm preferring javascript > jquery

当我使用鼠标滚轮滚动内容时,div我希望它滚动,例如,30px每个步骤或每个鼠标滚轮刻度 w/e 都是最好的解决方案。
我更喜欢performance > ease即我更喜欢javascript > jquery

回答by Amadan

There's big problems in implementing mousewheel details yourself, since there is (AFAIK) three different behaviours that the browsers are currently doing. Everything but Firefox currently supports mousewheelevent, which passes a wheelDeltaparameter of 120 per "click". Firefox has DOMMouseScrollevent, that will pass a detailparameter of 3 (I think) per "click", and in the opposite direction. Apple devices have a much more granular resolution, and have a deceleration to them; so Webkit browsers give also delta in the two axes, and there are no "clicks" on a trackpad two-fingered scroll. Finally, DOM Level 3 Events draft standard will define a "click" being (I think) 1, and provide a possibility of three axes; so you need to future-proof your code. So implementing your own wheel handler is kind of a pain (I know since I am now implementing zooming for my SVG app using the mousewheel).

自己实现鼠标滚轮细节存在很大问题,因为浏览器当前正在执行(AFAIK)三种不同的行为。除了 Firefox 之外的所有东西目前都支持mousewheel事件,wheelDelta每次“点击”传递一个120的参数。Firefox 有DOMMouseScroll事件,它将通过detail每次“点击”参数为 3(我认为),并且方向相反。Apple 设备有更精细的分辨率,并且有一个减速;所以 Webkit 浏览器在两个轴上也给出了 delta,并且在触控板的双指滚动上没有“点击”。最后,DOM Level 3 Events 草案标准将定义一个“点击”为(我认为)1,并提供三个轴的可能性;所以你需要让你的代码面向未来。所以实现你自己的滚轮处理程序有点痛苦(我知道,因为我现在正在使用鼠标滚轮为我的 SVG 应用程序实现缩放)。

You can consult Javascript: The Definitive Guide, chapter 17.6 Mousewheel Events, for more details.

您可以查阅 Javascript: The Definitive Guide,第 17.6 章鼠标滚轮事件,了解更多详细信息。

回答by skmasq

So I fiddled some solution of my own, you can see example here
Thanks Tomfor leading me to this answer.

所以我摆弄了一些我自己的解决方案,你可以在这里看到例子
感谢汤姆引导我找到这个答案。

JS:

JS:

function wheel($div,deltaY){
   var step = 30;
   var pos = $div.scrollTop();
   var nextPos = pos + (step*(-deltaY))
   console.log("DelatY: " + deltaY + ", Step: " + step + ", nextPos: " + nextPos);
   $div.scrollTop(nextPos);
}

$('#test').bind('mousewheel', function(event, delta, deltaX, deltaY) {
    wheel($(this),deltaY);
    event.preventDefault();
});

Used libraries:

使用的库:

  • jQuery 1.8.3
  • jQuery mousewheel
  • jQuery 1.8.3
  • jQuery 鼠标滚轮