此JavaScript只会以一种方式更改颜色。我怎么能这样做只有一个按钮可以暗/一次选择,取决于你选择哪个按钮?
这是我网站上的一个小型登录窗口,我试图让它在两个标签/菜单之间切换。任何帮助将不胜感激!
var login = document.querySelector('#login');
var signup = document.querySelector('#signup');
login.onclick = function() {
if (login.style.backgroundColor === "#a8661f") {
login.style.backgroundColor = "#d18029";
} else {
login.style.backgroundColor = "#a8661f"
}
signup.onclick = function() {
signup.style.backgroundColor = "#a8661f";
}
}
#log_in_box {
margin-top: 100px;
text-decoration: none;
margin-bottom: 100px;
font-size: 20px;
font-weight: bold;
}
#log_in_box button {
margin-top: 30px;
display: inline-block;
font-weight: bold;
font-size: 20px;
right: 5px;
position: relative;
bottom: 85px;
color: white;
border: 5px solid #a8661f;
border-radius: 20px 20px 0 0;
padding: 10px;
}
#login {
background-color: #d18029;
}
#signup {
background-color: #d18029;
}
<div id="log_in_box">
<div class="box">
<button id="login" onclick="login()">Log In</button>
<button id="signup" onclick="signup()">Sign Up</button>
<h1>Username:</h1>
<div class="type_box">
<p>enter your username</p>
</div>
<h1>Password:</h1>
<div class="type_box">
<p>enter your password</p>
</div>
</div>
</div>
答案 0 :(得分:0)
您可能更容易使用onfocus
和onblur
。试试下面的代码,看看是否是想要的结果:
var login = document.querySelector('#login');
var signup = document.querySelector('#signup');
login.onfocus = function() {
login.style.backgroundColor = "#a8661f";
}
login.onblur = function() {
login.style.backgroundColor = "#d18029";
}
signup.onfocus = function() {
signup.style.backgroundColor = "#a8661f";
}
signup.onblur = function() {
signup.style.backgroundColor = "#d18029";
}
答案 1 :(得分:0)
您可以根据当前处于活动状态的按钮切换按钮颜色来在颜色之间来回切换
var login = document.querySelector('#login');
var signup = document.querySelector('#signup');
login.onclick = function(){
login.style.backgroundColor = "#a8661f";
signup.style.backgroundColor = "#d18029";
}
signup.onclick = function(){
signup.style.backgroundColor = "#a8661f";
login.style.backgroundColor = "#d18029";
}
答案 2 :(得分:0)
更优化的解决方案
var login = document.querySelector('#login');
var signup = document.querySelector('#signup');
function changeColor(elem1, elem2) {
elem1.style.backgroundColor = "#a8661f";
elem2.style.backgroundColor = "#d18029";
}
login.onclick = function() {
changeColor(login, signup);
}
signup.onclick = function() {
changeColor(signup, login);
}
我希望它有所帮助。