Rob*_*ham 1 javascript jquery jquery-mobile jquery-slider
我花了2个小时的时间来尝试从不同来源的随机代码,声称他们已经设法将滑块捕捉到特定点.我不确定这是否适用于jQuery Mobile库,因为jQuery UI版本确实支持它,但我真的需要为当前项目找出一些东西.
基本上我有一个不同日期的时间表.它们不是"步骤",如10或20,它们是不同的数字.像1,3,10,12,32这样的东西.我需要滑块来捕捉这些点.
目前,我有一些东西正在测试步骤attr.
$('#slider-1').live( "change", function(e) {
var step = $(this).attr('step'),
val = $(this).val();
if(step % val == step || val == step){
console.log(val)
}
});
Run Code Online (Sandbox Code Playgroud)
我正在使用滑块的问题,不仅仅是捕捉,当我在20或40或60等附近滑动时,我正在获得控制台日志.它没有登录20等
在经过多次代码迭代后读出来并阅读我可以绑定的特定事件的文档.
所以基本上我的数组中有一个数字时间轴,看起来像:
-0--10--20 ----- --- 70--100 150 --- --- 200 --- 250 --- 300 --- 350 400 500 ----- --- ------------- 1000
我需要根据滑块手柄的位置捕捉到最近的数字.我通过测试当滑块移动到阵列中最接近的数字时的当前值来做到这一点.然后我会动态更改滑块值,然后必须强制刷新滑块以查看更改.
$(function() {
/*
Array of values between 0 - 1000 (can be any set of numbers you want to snap to,
but you must make sure the 'max' attribute on the input element is <= the last
value in the array)
*/
var values = [0, 10, 20, 70, 100, 150, 200, 250, 300, 350, 400, 500, 1000],
/*
A way for us to check the current and previous values of the slider so we only
call doSomething() if these are different. This way the function isn't called twice. These should NOT have the same values on init.
*/
currentVal = 0,
prevVal = null,
// Assign our slider to a variable so we're not hitting the dom repeatedly.
$slider = $("#slider-1");
/*
After each change of our input value, we assign the slider value to the nearest number
in our array for our "snap" effect
*/
$($slider).bind("change", function(){
$($slider).val(findNearest($($slider).val()))
});
/*
We must capture click events on the slider itself if the user doesn't drag the handle.
*/
$(".ui-slider[role=application]").bind("vclick",function(){
$($slider).slider('refresh');
})
/*
jQuery creates new dom elements for us, which in the case of the handle, is an anchor element.
Use mouseup method to test on the computer, otherwise touchend method for mobile devices.
*/
$("a.ui-slider-handle").touchend(function(){
// If our currentVal hasn't changed after a snap action, do nothing, otherwise call doSomething()
if(currentVal != prevVal) {
prevVal = currentVal;
doSomething();
}
// Force slider refresh for visible snap effect
$($slider).slider('refresh');
})
// Used to iterate over our array and check for nearest value to what is passed in
function findNearest(goal) {
var closest = null;
$.each(values, function(){
if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) {
closest = this;
}
});
return currentVal = Number(closest);
}
function doSomething(){
...
}
});
Run Code Online (Sandbox Code Playgroud)
我的HTML:
<label for="slider-1" id="slider_label_1">Input slider:</label>
<input type="range" name="slider-1" id="slider-1" value="0" min="0" max="1000" step="10" />
Run Code Online (Sandbox Code Playgroud)