首页 > 解决方案 > 触发输入键时更改按钮样式

问题描述

我是 HTML/CSS 和 JavaScript 的初学者。

我想button通过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>

标签: javascripthtmlcss

解决方案


在里面添加这个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();
}

推荐阅读