【发布时间】:2013-12-15 19:20:49
【问题描述】:
我有 2 个相互依赖的滑块。 2 个滑块的最大值为 100。如果第一个的值为 40%,则第二个的值将设置为 60%。但是,我需要在同一页面上出现两组上述场景。我试过了:Jsfiddle
第一组滑块只应该相互依赖,这应该在第二组中复制。但是,我遇到了一个问题,即第一组滑块中的第一个滑块和第二个滑块会影响第二组滑块。
(html):
First set
<ul id="sliders">
<li>
<div class="slider">70</div>
<span class="value">0</span>%
</li>
<li>
<div class="slider">30</div>
<span class="value" >0</span>%
</li>
</ul>
second set
<ul id="sliders2">
<li>
<div class="slider2">70</div>
<span class="value">0</span>%
</li>
<li>
<div class="slider2">30</div>
<span class="value" >0</span>%
</li>
</ul>
Javascript:
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) + 1;
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);
});
}
});
});
var sliders = $("#sliders2 .slider2");
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) + 1;
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);
});
}
});
});
我的直觉是var sliders = $("#sliders2 .slider2"); 没有检索到第二组滑块...
-----解决了---- 我已将我的代码编辑为 Swires 指出的内容。还将代码更新为数学部分的正确公式。新小提琴:The correct version
【问题讨论】:
标签: jquery jquery-ui slider range jquery-ui-slider