我有3个按钮:按钮1,按钮2和按钮3.按钮1切换左侧的显示/隐藏。按钮2执行相同但右侧。按钮3执行双方。这样做的正确方法是什么?
https://jsfiddle.net/anthony0perez/m9h2n1vk/2/
<div id="list-map-button" class="btn map-btn">LIST</div>
<div id="map-map-button" class="btn map-btn">MAP</div>
<div id="both-map-button" class="btn map-btn map-btn-active">BOTH</div>
<br style="clear:both;"/>
<div class="container">
<div id="left_side">
map side
<div id="block-3">Block 3</div>
<div id="block-4" class="not-active-block">Block 4</div>
</div>
<div id="right_side">
list side
<div id="block-5">Block 5</div>
<div id="block-6" class="not-active-block">Block 6</div>
</div>
<br style="clear:both;"/>
</div>
$(document).ready(function(){
$( "#both-map-button" ).click(function() {
//alert('clicked both button');
$("#block-4, #block-3, #block-5, #block-6").hide();
$("#block-4, #block-3, #block-5, #block-6").addClass("acvite-btn");
$("#block-4, #block-3").show();
$("#block-5, #block-6").show();
});
$( "#map-map-button" ).click(function() {
//alert('clicked map button');
$("#block-5").toggle();
$("#block-6").toggle();
});
$( "#list-map-button" ).click(function() {
//alert('clicked list button');
$("#block-4").toggle();
$("#block-3").toggle();
});
});
答案 0 :(得分:1)
您可以简单地使用单个变量来保存您的州。请注意,我为该示例对循环进行了硬编码,因为我们总是处理三个按钮。
inputs = document.getElementsByTagName('input');
state = 0;
for (var i = 0; i < 3; i++) {
(function(i) {
inputs[i].addEventListener('click', function() {
state ^= (i + 1);
for (var j = 1; j < 3; j++) {
inputs[j - 1].classList.toggle('on', (j & state));
}
});
}(i));
}
input {
background: lightgray
}
input.side {
background: red
}
input.on {
background: limegreen
}
<input type="button" class="side" value="toggle left" />
<input type="button" class="side" value="toggle right" />
<input type="button" value="toggle both" />
如果您打算将两个切换打开(如果已经打开),您只需添加一个单独的检查。
if (i & 2) {
state = ~~(state > 0) * 3;
}