有两个具有相同类别的按钮
<button class="show-hide-sidebar">Cart</button>
<button class="show-hide-sidebar">Wish</button>
我正在尝试显示和隐藏侧边栏,但如果侧边栏已经打开,我想保持它打开!此代码分别在每个项目上运行良好,但如果我单击
Cart
btn 并想要检查 Wish
,它会关闭侧边栏
$(".show-hide-sidebar").on("click", function () {
// Check if the sidebar is already visible (has the 'sidenav-show' class)
if ($("#sidebar").hasClass('sidenav-show')) {
// If sidebar is open, close it
$("#sidebar").removeClass("sidenav-show").addClass("sidenav-hide");
$("#mainbar").removeClass("main-narrow").addClass("main-wide");
} else {
// If sidebar is closed, open it
$("#sidebar").removeClass("sidenav-hide").addClass("sidenav-show");
$("#mainbar").removeClass("main-wide").addClass("main-narrow");
}
});
$(".show-hide-sidebar").on("click", function () {
// Check if the sidebar is already visible (has the 'sidenav-show' class)
if ($("#sidebar").hasClass('sidenav-show')) {
// If sidebar is open, close it
$("#sidebar").removeClass("sidenav-show").addClass("sidenav-hide");
$("#mainbar").removeClass("main-narrow").addClass("main-wide");
} else {
// If sidebar is closed, open it
$("#sidebar").removeClass("sidenav-hide").addClass("sidenav-show");
$("#mainbar").removeClass("main-wide").addClass("main-narrow");
}
});
.box{
height:60px;
width:60px;
margin:20px
}
.sidenav-show{
background:red
}
.sidenav-hide{
background:gold
}
.main-narrow{
background:red
}
.main-wide{
background:gold
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<button class="show-hide-sidebar">Cart</button>
<button class="show-hide-sidebar">Wish</button>
<div class="box sidenav-show" id="sidebar"> </div>
<div class="box main-narrow" id="mainbar"> </div>
我的做法是为您的按钮添加一个唯一的标识符。 类似的东西
<button id="Cart" class="show-hide-sidebar">Cart</button>
<button id="Wish" class="show-hide-sidebar">Wish</button>
然后添加一个变量来跟踪单击的按钮
var btnClicked = '';
拆分您的点击事件并拉出切换开关
$("#Cart").on("click", function () {
if(btnClicked != 'Cart'){
btnClicked = 'Cart';
toggleSideBar();
}
}
$("#Wish").on("click", function () {
if(btnClicked != 'Wish'){
btnClicked = 'Wish';
toggleSideBar();
}
}
那么你的切换方法就是剩下的了
function toggleSideBar(){
// Check if the sidebar is already visible (has the 'sidenav-show' class)
if ($("#sidebar").hasClass('sidenav-show')) {
// If sidebar is open, close it
$("#sidebar").removeClass("sidenav-show").addClass("sidenav-hide");
$("#mainbar").removeClass("main-narrow").addClass("main-wide");
} else {
// If sidebar is closed, open it
$("#sidebar").removeClass("sidenav-hide").addClass("sidenav-show");
$("#mainbar").removeClass("main-wide").addClass("main-narrow");
}
}