带停止点的滑块 [英] Slider with stop points
问题描述
我想创建一个具有一些停止点的滑块.每当我单击任何项目时,我都希望滑块在那一刻跳起来并执行一些操作.我已经使用jQuery UI的滑块创建了滑块.这很简单,但是我不完全知道如何添加这些停止点.是否有为此准备的现成的库,还是我应该自己实现?如果是这样,您能帮我走上正轨吗?
I want to create a slider which has some stop points. Whenever I click on any item, I want the slider to jump at that point and do some action. I have created the slider with jQuery UI's slider. It's pretty easy, but I don't exactly know how to add those stop points. Is there a ready-made library for this or should I implement this myself? If so, could you please help me get on track?
推荐答案
我之前做了类似的事情.基本上是这样的:
I did something similar to this before. It's basically working like this:
- 我将所有可能的值存储在一个数组中(在我的情况下为"关键帧",就像您的"停止点"一样)
- 滑块的
stop()
回调触发名为_getClosest
的函数并设置新值 - 单击滑块下方的链接,使其直接跳至该位置
- I store all possible values in an array (in my case "keyframes" like your "stop points")
- the
stop()
-callback of the slider triggers a function called_getClosest
and sets the new value - a click on the links below the slider let the it jump directly to that position
演示
HTML
<div id="slider"></div>
<div id="keyframes">
<a>|</a><a>|</a><a>|</a><a>|</a><a>|</a><a>|</a><a>|</a>
</div>
滑块,链接和关键帧
var slider = $('slider');
var links = $('#keyframes > a');
var values = [0, 10, 34, 67, 80, 85, 100];
// initiate slider
slider.slider({
value: 0,
min: 0,
max: 100,
animate: 500,
stop: function( event, ui ) {
slider.slider('value', _getClosest(ui.value) );
}
});
// add click to the links
links.click(function() {
slider.slider('value', values[$(this).index()]);
});
如何获取最接近的元素
最简单的方法是将当前滑块位置与可能的关键帧进行比较:
The easiest way is to compare the current slider position to the possible keyframes:
- 如果我已经走了一半或更远,我将移至下一个元素
- 如果我还没到达中间,我会回到之前的元素
所以_getClosest()
看起来可能像这样:
So _getClosest()
can look like this:
function _getClosest(value) {
var closest = null;
$.each(values, function(_key, _value) {
if (closest == null || Math.abs(this-value) < Math.abs(closest-value)) {
closest = this;
}
});
return closest;
}
将链接对应于其值放置在滑块下方
要将链接放置在它们各自的位置,只需循环遍历它们,并根据values
数组中的值设置左偏移量.这次我将值乘以2
,因为演示中的滑块的宽度为200px
,但范围为0-100
:
To place the links at their respective position, simply loop thru them and set the left offset according to the values from the values
-array. This time I multiplied the value with a factor of 2
because the slider in the demo is 200px
wide but has a range from 0-100
:
$.each(links, function(key, value) {
$(value).css('left', values[key] * 2);
});
这篇关于带停止点的滑块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!