我需要在 Blazor 项目中设计按钮(我使用的是引导程序)。我在一个 Razor 页面上有 2 个按钮组。每组 3 到 4 个按钮。我想用Javascript来改变onclick函数的颜色按钮。
用户将单击组 1 中的任何按钮(单击将颜色更改为绿色时)并单击组 2 中的按钮,而不会取消选择组 1 中的按钮。
onclick 调用需要在此处 <div class="btn-group">
因为我的按钮上已经有了 onclick<button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(13)">@Language.T37</button>
我在 CSS 中尝试过 :focus
,但只能选择 1 个按钮。
这是我的代码,为了测试目的,我去掉了 onclick in 按钮。
.btn:hover {
font-weight: bold;
color: white;
/*green*/
background-color: #85c995;
}
<div class="row">
<div class="column" style="width:30%">
<div class="btn-group">
<button type="button" class="btn btn-primary" style="outline-color:red; ">Sunday</button>
<button type="button" class="btn btn-primary">Tuesday</button>
<button type="button" class="btn btn-primary">Friday</button>
</div>
</div>
<div class="column" style="width:70%">
<div class="btn-group">
<button type="button" class="btn btn-primary">9 am</button>
<button type="button" class="btn btn-primary">2 pm</button>
<button type="button" class="btn btn-primary">5 pm</button>
<button type="button" class="btn btn-primary">8 pm</button>
</div>
</div>
</div>
答案 0 :(得分:0)
function switch_to_green(el){
//Check clicked button is on the same group
if(el.parentElement.getAttribute("data-group") == 1){
//Get all buttons of group 1
let g1_buttons = document.querySelectorAll('#group1 .btn');
for(let i =0; i<g1_buttons.length;i++){
//Remove green color from unselected buttons
g1_buttons[i].classList.remove('green');
}
}else{
//Get all buttons of group 2
let g2_buttons = document.querySelectorAll('#group2 .btn');
for(let i =0; i<g2_buttons.length;i++){
//Remove green color from unselected buttons
g2_buttons[i].classList.remove('green');
}
}
//Add green color to the only selected one
el.classList.add('green');
}
.btn:hover {
font-weight: bold;
color: white;
/*green*/
background-color: #85c995;
}
.btn.green{
color: white;
/*green*/
background-color: #85c995;
}
<div class="row">
<div class="column" style="width:30%">
<div class="btn-group" id="group1" data-group="1">
<button type="button" class="btn btn-primary" style="outline-color:red; " onclick="switch_to_green(this)">Sunday</button>
<button type="button" class="btn btn-primary" onclick="switch_to_green(this)">Tuesday</button>
<button type="button" class="btn btn-primary" onclick="switch_to_green(this)">Friday</button>
</div>
</div>
<div class="column" style="width:70%">
<div class="btn-group" id="group2" data-group="2">
<button type="button" class="btn btn-primary" onclick="switch_to_green(this)">9 am</button>
<button type="button" class="btn btn-primary" onclick="switch_to_green(this)">2 pm</button>
<button type="button" class="btn btn-primary" onclick="switch_to_green(this)">5 pm</button>
<button type="button" class="btn btn-primary" onclick="switch_to_green(this)">8 pm</button>
</div>
</div>
</div>