Combined total for multiple jQuery-UI Sliders

后端 未结 6 1244
情深已故
情深已故 2020-11-29 08:02

I\'m trying to implement a page where there are 4 jQuery-UI sliders, and I want to make it so the combined total of all 4 sliders will never go over 400.

I don\'t mi

6条回答
  •  情话喂你
    2020-11-29 08:23

    Made an updated version of the above answer to show percentages of 100%. So as you adjust one slider up, the other two decrease making the percentage of each slider add up to 100%. Also made it easy to set initial values

    JSfiddle

    var sliders = $("#sliders .slider");
    var availableTotal = 100;
    
    sliders.each(function() {
        var init_value = parseInt($(this).text());
    
        $(this).siblings('.value').text(init_value);
    
        $(this).empty().slider({
            value: init_value,
            min: 0,
            max: availableTotal,
            range: "max",
            step: 2,
            animate: 0,
            slide: function(event, ui) {
    
                // Update display to current value
                $(this).siblings('.value').text(ui.value);
    
                // Get current total
                var total = 0;
    
                sliders.not(this).each(function() {
                    total += $(this).slider("option", "value");
                });
    
                // Need to do this because apparently jQ UI
                // does not update value until this event completes
                total += ui.value;
    
                var delta = availableTotal - total;
    
                // Update each slider
                sliders.not(this).each(function() {
                    var t = $(this),
                        value = t.slider("option", "value");
    
                    var new_value = value + (delta/2);
    
                    if (new_value < 0 || ui.value == 100) 
                        new_value = 0;
                    if (new_value > 100) 
                        new_value = 100;
    
                    t.siblings('.value').text(new_value);
                    t.slider('value', new_value);
                });
            }
        });
    });
    

提交回复
热议问题