我是HTML / CSS和JavaScript的初学者。我想通过ENTER键触发一个按钮。问题是,当我将鼠标悬停在该按钮上或单击它时,它会更改背景颜色,而输入“ ENTER”键却不会。 我想在按ENTER键时更改按钮的背景颜色。
document.getElementById("password").addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("buttonpw").click();
}
});
function mypassword() {
var x = document.getElementById("password").value;
if (x === "SolitaryRJin") {
alert("It's not for You. Bye bye!!");
} else {
alert("It's not for You. Bye bye!!");
}
}
button {
position: absolute;
z-index: 100;
width: 149px;
height: 43px;
border: 1px solid #fff;
background: #000;
font-family: 'Roboto', sans-serif;
color: #fff;
font-size: 16px;
border-radius: 22px;
transition: 0.5s;
cursor: pointer;
margin: 0;
position: absolute;
top: 80%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
button:hover {
color: #000;
background: #fff;
}
button:focus {
outline-width: 0;
}
<input id='password' class='pass' onfocus="" class='inc1' type="password" name="Password" placeholder='Password' value="">
<button id='buttonpw' onclick="mypassword()">Sign In</button>
答案 0 :(得分:0)
将此内容添加到if
-document.getElementById("buttonpw").setAttribute("style", "color: #000;background: #fff;");
像这样:
if (event.keyCode === 13) {
document.getElementById("buttonpw").setAttribute("style", "color: #000;
background: #fff;");
document.getElementById("buttonpw").click();
}
答案 1 :(得分:0)
您可以单击Enter添加类,并在CSS中使用类名。
编辑!
在您的评论中更改样式,然后使用setTimeout
:https://www.w3schools.com/Jsref/met_win_settimeout.asp
document.getElementById("password")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
var element =document.getElementById("buttonpw");
element.click();
}
});
function mypassword(){
setTimeout(function(){
alert('you did it!');
},500);
var element =document.getElementById("buttonpw");
element.classList.add("clicked");
}
button {
position: absolute;
z-index: 100;
width: 149px;
height: 43px;
border: 1px solid #fff;
background: #000;
font-family: 'Roboto', sans-serif;
color: #fff;
font-size: 16px;
border-radius: 22px;
transition: 0.5s;
cursor: pointer;
margin: 0;
position: absolute;
top: 80%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
button:hover, .clicked{
color: #000;
background: #fff;
}
button:focus {
outline-width: 0;
}
<html>
<input id='password' class='pass' onfocus="handle1()" class='inc1' type="password" name="Password" placeholder='Password' value="">
<button id='buttonpw' onclick="mypassword()">Sign In</button>
</html>