我需要创建多个jQuery UI滑块,而每个滑块都有不同的值。所有滑块值都加在一起,并且不能超过最大值11.000。
我的问题:存在一个错误:滑块(例如第一个)向结果中添加的值少于其自身值(100)。这不可能。
要重现此内容,请设置以下值:
滑块1:58($ 5.800)和滑块2:74($ 5.180)
现在总计为$ 10.980,这很好。如果现在向右拖动滑块1多一点,将添加20个而不是100个。由于max为11k,因此滑块现在应该返回false,并且不能向右拖动。
function number_format(number, decimals, decPoint, thousandsSep) {
decimals = decimals || 0;
number = parseFloat(number);
if (!decPoint || !thousandsSep) {
decPoint = '.';
thousandsSep = ',';
}
var roundedNumber = Math.round(Math.abs(number) * ('1e' + decimals)) + '';
var numbersString = decimals ? roundedNumber.slice(0, decimals * -1) : roundedNumber;
var decimalsString = decimals ? roundedNumber.slice(decimals * -1) : '';
var formattedNumber = '';
while (numbersString.length > 3) {
formattedNumber += thousandsSep + numbersString.slice(-3)
numbersString = numbersString.slice(0,-3);
}
return (number < 0 ? '-' : '') + numbersString + formattedNumber + (decimalsString ? (decPoint + decimalsString) : '');
}
// https://stackoverflow.com/questions/3951726/jquery-slider-combined-values-having-difficulty-with-small-increments
jQuery(function() {
var maxValueSlider = 200,
maxValueTotal = 11000,
$sliders = jQuery(".prebate-calc .slider"),
valueSliders = [],
$displaySpentTotal = jQuery('.prebate-calc-result');
function arraySum(arr) {
var sum = 0, i;
for (i in arr) sum += arr[i];
return sum;
}
$sliders.each(function(i, slider) {
var $slider = jQuery(slider);
valueSliders[i] = 0;
$slider.slider({
range: 'min',
value: 0,
min: 0,
max: maxValueSlider,
step: 1,
animate: true,
slide: function(event, ui) {
var priceElement = jQuery(this).parent().next();
var getBasePrice = priceElement.data('each');
var sumRemainder = arraySum(valueSliders) - valueSliders[i],
adjustedValue = Math.min(maxValueTotal - sumRemainder, ui.value);
calculatedValue = Math.min(maxValueTotal - sumRemainder, ui.value*getBasePrice);
valueSliders[i] = calculatedValue;
priceElement.removeClass('prebate-calc-price-inactive');
priceElement.attr('data-price', calculatedValue);
priceElement.html('$ ' + number_format(calculatedValue, 0, ',', '.'));
// display the current total
$displaySpentTotal.html('Total prebate: $ ' + number_format(sumRemainder + calculatedValue, 0, ',', '.'));
// display the current value in tooltip
var slidertip = '<div class="slidertip-inner">' + Math.ceil(calculatedValue/getBasePrice) + '</div>';
jQuery('.ui-slider-handle', this).html(slidertip);
// console.log(sumRemainder + calculatedValue);
// stop sliding (return false) if value is equal to max
return (sumRemainder + calculatedValue) != maxValueTotal;
// set slider to adjusted value
$slider.slider('value', adjustedValue);
}
});
});
});
谢谢