我有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();
});
});发布于 2015-03-24 00:53:51
您可以简单地使用一个变量来保持状态。注意,我为这个例子硬编码了循环,因为我们总是处理三个按钮。
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;
}https://stackoverflow.com/questions/29220678
复制相似问题