gpt4 book ai didi

javascript - 在按键上更改 CSS 属性

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:32 26 4
gpt4 key购买 nike

我希望 javascript 代码在按键时更改 bat1 div 的“左”属性?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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com