2016-07-28 50 views
1

如何計算滑塊百分比(即<input type="range">),其總和爲100%;依賴輸入類型範圍的正確算法

在本例中,當我將第二個滑塊值設置爲95%時,其他滑塊值設置爲3%。如何解決它?

// Calculate fraction 
if (sum <= 0) { 
    fraction = 1/(depends.length - 1) 
} else { 
    fraction = val/sum; 
} 

// The last element will correct rounding errors 
if (i >= depends.length - 1) { 
    val = max - partial; 
} else { 
    val = Math.round(delta * fraction); 
    partial += val; 
} 

https://jsfiddle.net/vLaj37hf/

+0

設置 「步」 爲所有'input'成分爲 「2」,而不是 「5」 –

+0

我需要所有X5%的值 – Sasay

回答

2

你可以嘗試檢查,如果總的<input type="range">所有值比最高值是100更大。如果爲真,則可以找到差異並從最後一個值中減去它。這可能不是最好的解決方案。請看下面。

var depends = document.querySelectorAll('.depend'); 
 

 
[].forEach.call(depends, function(depend) { 
 
    depend.onchange = function() { 
 
    s(this, this.value); 
 
    c(this); 
 
    } 
 
}); 
 

 
function c(current) { 
 
    var input = current.value; 
 
    var max = 100; 
 
    var delta = max - parseInt(input); 
 
    var sum = 0; 
 
    var partial = 0; 
 
    var siblings = []; 
 

 
    // Sum of all siblings 
 
    [].forEach.call(depends, function(depend) { 
 
    if (current != depend) { 
 
     siblings.push(depend); // Register as sibling 
 
     sum += +depend.value; 
 
    } 
 
    }); 
 

 
    // Update all the siblings 
 
    siblings.forEach(function(subling, i) { 
 

 
    var val = +subling.value; 
 
    var fraction = 0; 
 

 
    // Calculate fraction 
 
    if (sum <= 0) { 
 
     fraction = 1/(depends.length - 1) 
 
    } else { 
 
     fraction = val/sum; 
 
    } 
 

 
    // The last element will correct rounding errors 
 
    if (i >= depends.length - 1) { 
 
     val = max - partial; 
 
    } else { 
 
     val = Math.round(delta * fraction); 
 
     partial += val; 
 
    } 
 

 
    // Check if total of all range is greater than max value 
 
    var total = partial + parseInt(input); 
 
    if (total > max) { 
 
     var diff = total - max; // Calculate the difference 
 
     val = val - diff; // Update the value 
 
     partial = partial - diff; 
 
    } 
 

 
    s(subling, val); 
 
    }); 
 
} 
 

 
function s(el, value) { 
 
    var label = document.getElementById(el.id + '_value') 
 
    label.innerHTML = value; 
 
    el.value = value; 
 
}
<input type="range" class="depend" min="0" max="100" value="70" step="5" id="one"> 
 
<label id="one_value">70</label>% 
 
<br> 
 
<input type="range" class="depend" min="0" max="100" value="30" step="5" id="two"> 
 
<label id="two_value">30</label>% 
 
<br> 
 
<input type="range" class="depend" min="0" max="100" value="0" step="5" id="three"> 
 
<label id="three_value">0</label>% 
 
<br>

+1

謝謝的,這是正確的,但不是5%步。我的決定是[這裏](https://jsfiddle.net/vLaj37hf/1/),但僅限於3個輸入。 – Sasay