CFXIXI工作室首页
CF西西的博客 | Range Input 三个插件联动

Range Input 三个插件联动

1. 七月 2016

参考:http://jsfiddle.net/EL4tf/

 

<input type="range" min="0" max="100" value="0" />
<input type="range" min="0" max="100" value="0" />
<input type="range" min="0" max="100" value="0" />

<div>total: <strong id="total">0</strong>/150</div>







var maxTotal = 150, 
    inputs = [].slice.call(document.getElementsByTagName('input')),
    getTotal = function(){
        var sum = 0;
        inputs.forEach( function(input){
           sum += parseInt(input.value, 10); 
        });
        return sum;
    },
    maxReached = function(e){
        var sum = getTotal(), target;
        if(sum > maxTotal){
            target = e.target;
            target.value = target.value - (sum - maxTotal);
            // next line is just for demonstrational purposes
            document.getElementById('total').innerHTML = getTotal();
            e.preventDefault();
            return false;
        }
        // next line is just for demonstrational purposes
        document.getElementById('total').innerHTML = getTotal();
        return true;
    };

inputs.forEach( function(input){
    input.addEventListener('input', maxReached );
});

综合