gpt4 book ai didi

Javascript:document.getElementById() 返回 NULL

转载 作者:技术小花猫 更新时间:2023-10-29 12:35:41 24 4
gpt4 key购买 nike

我是 Javascript 的新手,我遇到了一个总是返回 NULL 的 document.getElementById() 问题,这让我抓狂。

我的代码中有一个元素,我想获取它的坐标以便移动它。

代码如下:

<html>
<head>
<script type="text/javascript" >
function MoveIt(obj) {
alert(obj); // returns "Object HTMLDivElement"
var xx = document.getElementById("arect");

if(document.getElementById("arect").value == null) {
alert('NULL >> ' + xx.value);
}
else {
alert('NOT NULL >>' + xx.value);
}

posX = xx.style.scrollTop;
posY = xx.style.left;
}
</script>
</head>

<body bgcolor="white" >
<DIV class="background" id="MyDiv2">
<div id="arect" name="arect" class="transbox" onmousedown="MoveIt(this);" >
</div>
</div>
</body>
</html>

上面的函数 MoveIt() 总是返回 NULL

最佳答案

在尝试阅读之前需要加载页面内容。尝试

window.onload = function() {
// run your script in here
}

或者,如果您使用的是 jQuery,则更喜欢

$(document).ready(function() {
...
}

关于Javascript:document.getElementById() 返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6112343/

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