如何给点击的button添加高亮?点击切换样式
html代码:
<div id="eventSystem">
<button class="choice choiceCss" id="system0" onclick="choosed(this)">防撞和界限监测</button>
<button class="choice choiceCss" id="system1" onclick="choosed(this)">障碍物检测</button>
<button class="choice choiceCss" id="system2" onclick="choosed(this)">LCU</button><button class="choice choiceCss" id="system3" onclick="choosed(this)">弓网监测</button><button class="choice choiceCss" id="system4" onclick="choosed(this)">接触网巡检</button>
<button class="choice choiceCss" id="system5" onclick="choosed(this)">轨道几何检测</button>
<button class="choice choiceCss" id="system6" onclick="choosed(this)">轨道巡检</button><button class="choice choiceCss" id="system7" onclick="choosed(this)">隧道巡检</button><button class="choice choiceCss" id="system8" onclick="choosed(this)">ATC
</button><button class="choice choiceCss" id="system9"onclick="choosed(this)">TCMS</button>
<button class="choice choiceCss" id="system10" onclick="choosed(this)">牵引</button><button class="choice choiceCss" id="system11" onclick="choosed(this)">辅助</button><button class="choice choiceCss" id="system12" onclick="choosed(this)">制动</button><button class="choice choiceCss" id="system13" onclick="choosed(this)">空调</button><button class="choice choiceCss" id="system14" onclick="choosed(this)">车门</button><button class="choice choiceCss" id="system15" onclick="choosed(this)">乘客信息</button>
<button class="choice choiceCss" id="system16" onclick="choosed(this)">走行部</button><button class="choice choiceCss" id="system17" onclick="choosed(this)">蓄电池监测</button>
</div>
js代码:
function choosed(e){
var choice = $(e).attr("id");//获取点击按钮 id
var buttonList = document.getElementByClassName("choice ");//获取相同 class 的兄弟元素(首先需要为所有的兄弟元素添加相同的class)
for(var i = 0; i<buttonList.length; i++){
//遍历后移除高亮class
buttonList[i].classList.remove("this_selected")
}
// 为点击的按钮添加 高亮 class
document.getElementById(choice).classList.add("this_selected");
}
这里有个知识点:以上用法不能直接用addClass或者removeClass方法,故用到了classList,该属性返回元素的class的类名,在此指"choice choiceCss";在此基础上调用add(),remove()方法。
css代码:
.choiceCss{
background: #012C3F;
}
.this_selected{
color:#FFFFFF!important;
background: linear-gradient(270deg, #045D82 0%, #1697C9 100%);
}
在这里要注意css加载顺序,优先级。
如图;