[英]A set button starts clicked/active when page is opened/refreshed
我有一个小系统,如果我点击一个按钮,它会改变点击按钮的颜色,如果我点击另一个按钮,它会改变它的颜色,并将之前点击的按钮设置回原来的颜色。
我想要的只是在打开/刷新页面时将其中一个按钮设置为活动(单击)。 最好将登录设置为默认单击。
谢谢你是提前:)
HTML:
<div class="login-or-register-container">
<button class="button-categories">LOGIN</button>
<button class="button-categories">REGISTER</button>
</div>
CSS:
.login-or-register-container {
display: flex;
}
button.button-categories:hover {
border-bottom-width: 1px;
border-bottom-color: #1100ff;
}
button.button-categories {
font-size: 12px;
display: block;
width: 100px;
height: 40px;
color: #fff;
background-color: #555;
border: solid;
border-radius: 0px;
border-width: 1px;
border-color: #999;
text-align: center;
font-weight: 1000;
}
button.button-categories.active {
border-bottom-width: 2px;
border-bottom-color: #1100ff;
padding-top: 1px;
color: #1100ff;
}
Javascript:
// Get all the buttons into a node list
let buttons = document.querySelectorAll(".button-categories");
// Set an event handler on the document so that when
// any element is clicked, the event will bubble up to it
document.addEventListener("click", function(evt){
// Check to see if it was a button that was clicked
if(evt.target.classList.contains("button-categories")){
// Loop over all the buttons & remove the active class
buttons.forEach(function(button){
button.classList.remove("active");
});
// Make the clicked button have the active class
evt.target.classList.add("active");
}
});
如果您想让一个按钮在页面加载时默认处于活动状态,那么只需将active
类添加到该按钮即可。 喜欢:
// Get all the buttons into a node list let buttons = document.querySelectorAll(".button-categories"); // Set an event handler on the document so that when // any element is clicked, the event will bubble up to it document.addEventListener("click", function (evt) { // Check to see if it was a button that was clicked if (evt.target.classList.contains("button-categories")) { // Loop over all the buttons & remove the active class buttons.forEach(function (button) { button.classList.remove("active"); }); // Make the clicked button have the active class evt.target.classList.add("active"); } });
.login-or-register-container { display: flex; } button.button-categories:hover { border-bottom-width: 1px; border-bottom-color: #1100ff; } button.button-categories { font-size: 12px; display: block; width: 100px; height: 40px; color: #fff; background-color: #555; border: solid; border-radius: 0px; border-width: 1px; border-color: #999; text-align: center; font-weight: 1000; } button.button-categories.active { border-bottom-width: 2px; border-bottom-color: #1100ff; padding-top: 1px; color: #1100ff; }
<div class="login-or-register-container"> <button class="button-categories active">LOGIN</button> <button class="button-categories">REGISTER</button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.