gpt4 book ai didi

javascript - 无法获取 div 样式左值....

转载 作者:行者123 更新时间:2023-11-30 08:51:35 25 4
gpt4 key购买 nike

我刚刚开始学习 javascript,我正在尝试使用 javascript 移动一个 div 元素。我正在使用 style 的 left 和 top 属性来移动 div。代码如下。

html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>

<script>
window.onload = function() {

divObj = document.getElementById('divObj');

window.onkeydown=function(e) {
var keycode;
keycode = e.keyCode;
speed = 1;
if(keycode == 37) {
divObj.style.left = (parseInt(divObj.style.left) - speed) + "px"; }
else if(keycode == 38)
divObj.style.top = (parseInt(divObj.style.top) - speed) + "px";
else if(keycode == 39)
divObj.style.left = (parseInt(divObj.style.left) + speed) + "px";
else if(keycode == 40)
divObj.style.top = (parseInt(divObj.style.top) + speed) - "px";

}
}
</script>

<style>
div.div1 { width : 200px;
height :50px;
background-color : #333;
position:absolute;
left:0px;
top:0px;
}
</style>


</head>

<body>
<div id = "divObj" class = "div1"></div>

</body>
</html>

问题是“divObj.style.left”没有返回任何值,因此无法使用向上和向下键移动 div。

如果有人知道如何获取 div 的 style left 属性的值,请告诉我。

最佳答案

所有 else if 语句都需要单独的大括号

if(keycode == 37) {        
divObj.style.left = (parseInt(divObj.style.left) - speed) + "px"; }
else if(keycode == 38){
divObj.style.top = (parseInt(divObj.style.top) - speed) + "px";}
else if(keycode == 39){
divObj.style.left = (parseInt(divObj.style.left) + speed) + "px"; }
else if(keycode == 40){
divObj.style.top = (parseInt(divObj.style.top) + speed) - "px";}

关于javascript - 无法获取 div 样式左值....,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17467820/

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