我在一些可能有3、4或5个滑块的页面中使用NoUiSlider(http://refreshless.com/nouislider/)。
我需要将滑块设置为总值限制为100,这样,如果我提高滑块的值,其他滑块应该降低一点,反之亦然,但我真的不知道如何做到。
有人能帮我吗?谢谢
jQuery代码:
$(".slider.tied").each(function() {
var context = $(this).addClass("noUiSlider");
var input = context.prev(".amount"); // the input containing the actual slider value
var val = input.val();
var min = input.data("min");
var max = input.data("max");
context.noUiSlider({
range: [min, max],
start: val,
step: 1,
handles: 1,
slide: function() {
var value = $(this).val();
input.val(value);
}
});
});
一个可能的解决方案:
var init = true;
var elements = $(".multislider").children(".slider.tied").length;
var MAX = 100;
var initValue = (MAX / elements) >> 0;
var InitMod = MAX % elements;
$(".slider.tied").each(function() {
var slidersTied = $(".slider.tied");
var context = $(this);
var input = context.prev(".amount");
var val = input.data('answer');
var min = input.data('min');
var max = input.data('max');
var range = 1;
var proceed = false;
$(this).empty().slider({
value: val,
min: min,
max: max,
range: range,
animate: "slow",
create: function(event, ui){
if (InitMod > 0) {
$(this).slider('value', initValue + 1);
$(this).prev('.amount').val(initValue + 1);
InitMod = InitMod - 1;
}
else
{
$(this).slider('value', initValue);
$(this).prev('.amount').val(initValue);
}
},
slide: function(e, ui) {
// Update display to current value
$(this).prev('.amount').val(ui.value);
var current = ($(this).index() / 2) >> 0;
var total = 0;
var counter = 0
slidersTied.not(this).each(function() {
total += $(this).slider("option", "value");
counter += 1;
});
total += ui.value;
if (total != MAX){
proceed = true;
}
var missing = MAX - total;
console.log("missing: " + missing);
counter = 0;
if(proceed) {
//load elements array
var elements = [];
slidersTied.each(function() {
elements[counter] = $(this);
counter += 1;
});
var endIndex = counter - 1;
counter = endIndex + 1;
while (missing != 0) {
console.log("current counter: " + counter);
do {
if (counter == 0)
{
counter = endIndex;
}
else
{
counter = counter - 1;
}
} while(counter == current)
console.log("elemento attuale: " + counter);
var value = elements[counter].slider("option", "value");
var result = value + missing;
if (result >= 0)
{
elements[counter].slider('value', result);
elements[counter].prev('.amount').val(result);
missing = 0;
}
else
{
missing = result;
elements[counter].slider('value', 0);
elements[counter].prev('.amount').val(0);
}
}
}
}
});
});
这是一把小提琴:
http://jsfiddle.net/vuQz5/11/
注意将MAX变量的值设置为所需值(所有滑块值的总和…