我希望javascript代码在按键时更改bat1 div的'left'属性吗?
HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div id="bat1">

    </div>
    <script src="script.js"></script>
</body>
</html>


CSS:

#bat1{
    width: 150px;
    height: 20px;
    background-color: blue;
    position: relative;
    left: 10%;
}

最佳答案

您可以像这样为按键添加事件处理程序

function keyfunction(){
  document.getElementById("bat1").style.left = "300px";
}

document.addEventListener("keypress", keyfunction, false);




function keyfunction(){
  document.getElementById("bat1").style.left = "300px";
}

document.addEventListener("keypress", keyfunction, false);

#bat1{
    width: 150px;
    height: 20px;
    background-color: blue;
    position: relative;
    left: 10%;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div id="bat1">

    </div>
    <script src="script.js"></script>
</body>
</html>

关于javascript - 更改按键上的CSS属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59046427/

10-13 01:28