2 回答

TA貢獻(xiàn)1810條經(jīng)驗 獲得超4個贊
好的,所以您的代碼中有些錯誤...首先,您的JS(JavaScript)錯誤,語法
錯誤的方法
function onkeypress(evt);
if(onkeypress == 49)
正確的方法
function onkeypress(evt) {
if ( /* your condition */ ) {
/* your code */
}
}
另外,您需要在函數(shù)中添加一個偵聽器,該偵聽器將偵聽某個事件并調(diào)用一個函數(shù)(您的回調(diào)),您可以在此處閱讀更多內(nèi)容。要使用它就像:
document.addEventListener("keypress", onkeypress); // Add the listener
function onkeypress(e) {
/* Will handler your callback */
}
或者
document.addEventListener("keypress", (e) => {
/* Will handler your callback */
})
而且第二個snnipet中的CSS是錯誤的,您必須在<style></style>標(biāo)記內(nèi)使用它。并且您的<script></script>標(biāo)簽必須在正文的末尾,才能正常工作。嘗試下面的代碼。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" href="css/screen.css">
<style>
.toprectangle {
height: 80px;
width: 200px;
background-color: #1E90FF;
float:right;
margin: 0px 40px 20px 80px;
border: 1px solid #1E90FF;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="circle"></div>
<div class="circle1"></div>
<div class="toprectangle"></div>
<div class="square"></div>
<div class="square"></div>
<div class="box3"></div>
<div class="box2"></div>
<script>
document.addEventListener("keypress", onkeypress);
function onkeypress(e) {
console.log(`Letter: ${e.key} with code ${e.keyCode}`);
if (e.keyCode == 97) {
console.log('Letter `a` has been pressd!');
let toprectangle = document.getElementsByClassName("toprectangle");
console.log(toprectangle)
toprectangle[0].style.backgroundColor = "#000"
}
}
</script>
</body>
</html>
添加回答
舉報