jQuery 滑块“更改”事件:如何确定是谁调用了它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10255041/
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
jQuery slider “change” event: How do I determine who called it?
提问by eviabs
I got a slider that is used as a time-line in my music player. The min value is 0 and the max vlaue is the song length (in seconds). Each second (I do this with a timer), the slider moves and the value is set to the current time. This code line looks like that:
我有一个滑块,在我的音乐播放器中用作时间线。最小值为 0,最大值为歌曲长度(以秒为单位)。每一秒(我用计时器来做这个),滑块移动并且值被设置为当前时间。此代码行如下所示:
$("#sliderTime").slider("option", "value", document.sound.controls.currentPosition);
The user is able to slide/click the slider and jump to another point in the song, this is by firing the function 'play(startPlayFromHere)'. It looks like that:
用户可以滑动/单击滑块并跳转到歌曲中的另一个点,这是通过触发函数“play(startPlayFromHere)”来实现的。它看起来像这样:
$("#sliderTime").slider({
...
change: function (event, ui) { play(ui.value) },
});
The problem is that both the code line in the timer and the user are calling the same 'change' event of the the slider, and the user can't move the slider.
问题是计时器中的代码行和用户都在调用滑块的相同“更改”事件,而用户无法移动滑块。
So my question is how can I determine whether the user called the change event or not (that means it was the timer)?
所以我的问题是如何确定用户是否调用了更改事件(这意味着它是计时器)?
I hope it's clear enough, Thanks!
我希望它足够清楚,谢谢!
回答by Beetroot-Beetroot
You can determine whether a change event arose manually or programmatically by testing event.originalEvent
in the change handler.
您可以通过event.originalEvent
在更改处理程序中进行测试来确定更改事件是手动发生还是以编程方式发生。
$('#slider').slider({
change: function(event, ui) {
if (event.originalEvent) {
//manual change
play(ui.value);
}
else {
//programmatic change
}
}
});
See fiddle.
见小提琴。