如何为鼠标滚轮、jQuery 强制执行“平滑滚动”规则?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5560714/
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
How to enforce a "smooth scrolling" rule for mousewheel, jQuery?
提问by bnbgnoise
How are you? My Question:
你好吗?我的问题:
How can I control or specify the waya document scrolls to the position of desire described by either the mouse scrollwheel, and/or grabbing the scrollbar.
What I want would be to overcome the particular default method of page scrolling.
As it currently works the page jumps right to x# of pixels down per 'notch' that is progressed on the scrollwheel. Or goes directly to where you drag the scroll bar.
What i'm looking for is a simple extension to jquery that can apply certain scrolling rules.The principals are simple. Imposed acceleration, this would prevent the page from moving too fast without first accelerating. settable as a rate of in px/sec- with the option to apply easing functions...There is a maximum px/sec that the page can slide/move/drag. and thirdly is a deceleration rule, applied as the page approaches it's destination position (in %, px?). This may have to be calculated in one of many ways, and may be trickier. ie when scrolling the last 25 pixels to the destination position, the deceleration applys. There's more... The main concern I'd want to prepare for would be ensuring that small page scrolls we're supported fully and not glitchy.
What sort of jQuery approaches could be used to control the document in this way?
_kyle
我如何控制或指定文档滚动到由鼠标滚轮和/或抓取滚动条描述的期望位置的方式。我想要的是克服页面滚动的特定默认方法。
当它当前工作时,页面向右跳转到每个在滚轮上前进的“槽口”向下的 x# 个像素。或者直接转到您拖动滚动条的位置。我正在寻找的是 jquery 的一个简单扩展,它可以应用某些滚动规则。原理很简单。强制加速,这将防止页面在没有先加速的情况下移动得太快。可设置为 px/sec 的速率,可选择应用缓动功能...页面可以滑动/移动/拖动的最大 px/sec。第三是减速规则,当页面接近其目标位置时应用(以 %、px 为单位?)。这可能必须以多种方式之一计算,并且可能更棘手。即当滚动最后 25 个像素到目标位置时,减速适用。还有更多……我最关心的问题
什么样的 jQuery 方法可以用来以这种方式控制文档?_凯尔
Update::: Thanks For following this Q, if you are. Great News. Found a great plugin that hopefully can be handled to be supporting the desired effects, yo! I've implemented a whole page container and used this nifty jScrollPane script to commandeer if you will the scrolling of the page http://jscrollpane.kelvinluck.com/fullpage_scroll.html
更新:::感谢您关注此问题,如果您愿意的话。好消息。找到了一个很棒的插件,希望可以处理以支持所需的效果,哟!我已经实现了一个完整的页面容器,并使用这个漂亮的 jScrollPane 脚本来控制页面 http://jscrollpane.kelvinluck.com/fullpage_scroll.html
There is already a big difference in the performance of the page. Each scroll notch from the wheel is a third to a half of the browsers native scroll notch, so it moves slower, which is fine, surly that's adjustable.
We still have the stall-stall-stall method of page movement, though.
页面的性能已经有了很大的不同。滚轮上的每个滚动槽口都是浏览器原生滚动槽口的三分之一到一半,因此它移动得更慢,这很好,可以调节。
不过,我们仍然有页面移动的停顿停顿方法。
I myself write javascript, but more it's like I re-write it. What I think needs to be done is a "queue" built of pixels to be scrolled along a page, with the total time compounded: and then an animation footprint defined and executed as three phases, an in easing acceleration, maxscrollspeed phase, and decel phase.
我自己编写 javascript,但更像是我重新编写它。我认为需要做的是一个由像素构成的“队列”,沿着页面滚动,总时间复合:然后一个动画足迹定义和执行为三个阶段,在缓和加速阶段,maxscrollspeed阶段和减速阶段。
Could anybody offer any suggestions as to how we
任何人都可以就我们如何提供任何建议
Detatch the mousescrollwheel from its native function of scrolling the page.
listen for notches of the mousescroll; and in the event of a notch: initialize the corefunction to start the movement of the page, but also listen for and add additional notch clicks to "queue" that is re-calulated and applied to the scroll of the window replacing the previous totaldistancetoscroll, before calculating the next totaldistancetoscroll, which provides a way to anticipate the destination and decelerate. The corefunctions to start movement wouldn't want to be restarted, cause multiple notch clicks will probably happen while accelerating, but just a recalculated when and where to decelerate should be applied.
将 mousescrollwheel 从其滚动页面的本机功能中分离出来。
聆听鼠标滚轮的缺口;并且在出现缺口的情况下:初始化核心功能以开始页面的移动,但还要侦听并将额外的缺口点击添加到“队列”中,该“队列”被重新计算并应用于窗口的滚动,替换之前的 totaldistancetoscroll,在计算下一个 totaldistancetoscroll 之前,它提供了一种预测目的地和减速的方法。开始运动的核心功能不希望重新启动,因为加速时可能会发生多次缺口点击,但只需重新计算何时何地应该减速。
Sorry again for not posting any actual code yet, not exactly sure where to start and was hoping someone might know if mwintent will work for this and if so: might also have some ideas how to apply a deceleration to the scroll, which seems to be the only two difference between the desired effect and the state of the current plug-ins that are similar.
再次抱歉还没有发布任何实际代码,不确定从哪里开始,希望有人可能知道 mwintent 是否适用于此,如果是这样:可能还有一些想法如何对滚动应用减速,这似乎是所需效果和当前插件的状态之间唯一的两个区别是相似的。
回答by simo
What I wanted to do was to simulate browser's smooth scrolling on browsers that don't support it natively, has it turned off by default or has bad implementation of it.
我想要做的是在原生不支持它的浏览器上模拟浏览器的平滑滚动,默认情况下关闭它或者它的实现不好。
Thanks to lumbric's answer I've came up with this solution:
感谢 lumbric 的回答,我想出了这个解决方案:
$(function () {
var top = 0,
step = 55,
viewport = $(window).height(),
body = $.browser.webkit ? $('body') : $('html'),
wheel = false;
$('body').mousewheel(function(event, delta) {
wheel = true;
if (delta < 0) {
top = (top+viewport) >= $(document).height() ? top : top+=step;
body.stop().animate({scrollTop: top}, 400, function () {
wheel = false;
});
} else {
top = top <= 0 ? 0 : top-=step;
body.stop().animate({scrollTop: top}, 400, function () {
wheel = false;
});
}
return false;
});
$(window).on('resize', function (e) {
viewport = $(this).height();
});
$(window).on('scroll', function (e) {
if (!wheel)
top = $(this).scrollTop();
});
});
Put some content on your page long enough to have scrollbars. Then use your mouse wheel. It works on every browser. I've used jQuery-1.7.2 and the mousescroll plugin mentioned in the lumbric's post.
在页面上放置一些内容足够长的滚动条。然后使用鼠标滚轮。它适用于所有浏览器。我使用了 jQuery-1.7.2 和 lumbric 的帖子中提到的 mousescroll 插件。
The stepvar means how many pixels to scroll on every mouse wheel event. ~55 pixels is what I've found to be the default value on most systems.
该步VAR手段多少像素滚动每个鼠标滚轮事件。~55 像素是我发现大多数系统上的默认值。
Also you may want to change the speed for the animation, other than that the rest of the code logic is needed to get the things work properly.
此外,您可能想要更改动画的速度,除了需要其余的代码逻辑才能使事情正常工作。
EDIT:Note that I have extracted the above functionality into a convenience jquery plugin.
编辑:请注意,我已将上述功能提取到一个方便的jquery 插件中。
回答by lumbric
I had a very simmilar problem. I wanted to change the scroll function of a normal page. I want every scroll to be exactly of an specific height so that the page stops in very specific positions only.
我有一个非常相似的问题。我想更改普通页面的滚动功能。我希望每个卷轴都具有特定的高度,以便页面仅在非常特定的位置停止。
I realized it in the following way:
我通过以下方式实现了它:
1. Used Plugins
1. 使用过的插件
Download and include the following 2 jQuery plugins and jQuery itself:
下载并包含以下 2 个 jQuery 插件和 jQuery 本身:
- scrollTo(see also here)
- mousewheel(see also here)
2. Mousewheel event
2.鼠标滚轮事件
The easiest way is to use the mousewheel plug in that way:
最简单的方法是以这种方式使用鼠标滚轮插件:
$('body').mousewheel(function(event, delta) { /* code here */ });
The variable delta is then negative or positive, depending if the wheel was scrolled up or down. If you return falseI think (!) it disables the normal scroll.
变量 delta 是负数或正数,取决于滚轮是向上还是向下滚动。如果您返回false我认为(!)它会禁用正常滚动。
3. Scroll method
3.滚动方式
In order to scroll the page I used scrollTo, but any other plugin (like Smooth Scroll suggested in the other answer) should also do it.
为了滚动页面,我使用了 scrollTo,但任何其他插件(如其他答案中建议的 Smooth Scroll)也应该这样做。
4. Complete code
4.完整代码
Place this in the head part of you HTML-File:
把它放在你的 HTML 文件的头部:
<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="jquery.scrollTo-1.4.2-min.js"></script>
<script type="text/javascript" src="jquery.mousewheel.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('body').mousewheel(function(event, delta) {
# This if might not be very elegant!
if (delta < 0) {
$('body').scrollTo('+=100', 1500 );
}
else
$('body').scrollTo('-=100', 1500 );
return false;
});
});
</script>
5. Demo
5. 演示
I created a demo here: http://pastehtml.com/view/ba0ziusqk.html
我在这里创建了一个演示:http: //pastehtml.com/view/ba0ziusqk.html
回答by Benn
You want to give this one a try
你想试试这个
https://github.com/galambalazs/smoothscroll-for-websites
https://github.com/galambalazs/smoothscroll-for-websites
it has nice settings to adjust the animation and seems to be well maintained.
它有很好的设置来调整动画,而且似乎维护得很好。
// Scroll Variables (tweakable)
var defaultOptions = {
// Scrolling Core
frameRate : 100, // [Hz]
animationTime : 1200, // [ms]
stepSize : 80, // [px]
// Pulse (less tweakable)
// ratio of "tail" to "acceleration"
pulseAlgorithm : true,
pulseScale : 4,
pulseNormalize : 1,
// Acceleration
accelerationDelta : 50, // 50
accelerationMax : 3, // 3
// Keyboard Settings
keyboardSupport : true, // option
arrowScroll : 50, // [px]
// Other
touchpadSupport : false, // ignore touchpad by default
fixedBackground : true,
excluded : ''
};
回答by Irakli Dgebuadze
here is a good solution check this out http://ataredo.com/morphology/lucidscroll/
这是一个很好的解决方案,请查看http://ataredo.com/morphology/lucidscroll/
<script src="file-directory/jquery.js"></script>
<script src="file-directory/lucid.js"></script>
<script>
$(window).on('load', function() {
$(this).impulse();
});
</script>
回答by iKamy
my solution with Mobile effect
我的移动效果解决方案
<div id="parent">
<div id="child">aaa aaaaaaaaa aaaaaaaa aaaaaaaaaaaa abbbbbbbbbbbbbbbbb bbbbbbbbbbbbcc ccccccc ccccccccccc cccccccd ddddddd ddd ddddd ddddd dddddddd aaaaaaaaaaaa aaaaaaaa aaaaaaaaaaaa abbbbbbbbbbbbbbbbb bbbbbbbbbbbbcc ccccccc ccccccccccc cccccccd ddddddd ddd ddddd ddddd dddddddd aaaaaaaaaaaa aaaaaaaa aaaaaaaaaaaa abbbbbbbbbbbbbbbbb bbbbbbbbbbbbcc ccccccc ccccccccccc cccccccd ddddddd ddd ddddd ddddd dddddddd aaaaaaaaaaaa aaaaaaaa aaaaaaaaaaaa abbbbbbbbbbbbbbbbb bbbbbbbbbbbbcc ccccccc ccccccccccc cccccccd ddddddd ddd ddddd ddddd dddddddd aaaaaaaaaaaa aaaaaaaa aaaaaaaaaaaa abbbbbbbbbbbbbbbbb bbbbbbbbbbbbcc ccccccc ccccccccccc cccccccd ddddddd ddd ddddd ddddd dddddddd aaaaaaaaaaaa aaaaaaaa aaaaaaaaaaaa abbbbbbbbbbbbbbbbb bbbbbbbbbbbbcc ccccccc ccccccccccc cccccccd ddddddd ddd ddddd ddddd dddddddd aaaaaaaaaaaa aaaaaaaa aaa</div>
#parent {
width: 300px;
height: 300px;
background-color: #aaa;
margin: auto auto;
overflow: hidden;
}
#child {
width: 200px;
height: 800px;
background-color: #999;
margin: auto auto;
text-align: justify;
position: relative;
top: 0;
-webkit-transition: all 0.5s ease-out;
}
$('#parent').bind('mousewheel', function (e) {
if (!(e.originalEvent.wheelDelta == 120)) {
var top = parseInt($("#child").css("top"));
$("#child").css("top", (top - 100) + "px");
top = parseInt($("#child").css("top"));
if (top <= -500) {
setTimeout(function () {
$("#child").css("top", "-500px");
}, 100);
}
} else {
var top = parseInt($("#child").css("top"));
$("#child").css("top", (top + 100) + "px");
top = parseInt($("#child").css("top"));
if (top >= 0) {
setTimeout(function () {
$("#child").css("top", "0");
}, 100);
}
}
});
回答by Alex
Karl Swedberg has made a jQuery plugin called Smooth Scroll, which sounds like it may be just what you're after.
Karl Swedberg 制作了一个名为Smooth Scroll的 jQuery 插件,听起来它可能正是您所追求的。
回答by Ronen
var $window = $(window),
scrollDistance = 300,
scrollSpeed = 500,
scrollEffect = 'swing',
scrollAmount = 1,
smoothScroll;
if (! ('ontouchstart' in document.documentElement) && ! $('body').hasClass('modal-open')) {
$window.on("mousewheel DOMMouseScroll", function (event) {
event.preventDefault();
if (smoothScroll) {
// Start scrolling while waiting for final scoll amount (user stopped wheeling)
if (scrollAmount == 1) {
var delta = event.originalEvent.wheelDelta / 120 || -event.originalEvent.detail / 3;
var finalScroll = $window.scrollTop() - parseInt(delta * (scrollDistance * scrollAmount));
$('html, body').stop().animate({ scrollTop: finalScroll }, scrollSpeed, scrollEffect);
}
// Increase scroll amount
scrollAmount++;
// Clear current timeout
clearTimeout(smoothScroll);
}
// Set animated scroll
smoothScroll = setTimeout(function() {
var delta = event.originalEvent.wheelDelta / 120 || -event.originalEvent.detail / 3;
var scrollTop = $window.scrollTop();
var finalScroll = scrollTop - parseInt(delta * (scrollDistance * scrollAmount));
// Reset scroll amoount
scrollAmount = 1;
$('html, body').stop().animate({ scrollTop: finalScroll },
(scrollSpeed*scrollAmount),
scrollEffect
);
// Clear timeout holder
smoothScroll = null;
}, 100);
});
}