JavaScript的顶部和左侧位置没有按预期工作

JavaScript top and left positions not working as expected

本文关键字:工作 位置 顶部 JavaScript      更新时间:2023-09-26

我有这个代码在JavaScript上的HTML文件,但当我运行它的图像,我有不移动,当我改变顶部或左侧。为什么会发生这种情况,我已经搜索了几个小时,并复制了大量的代码,看看它是否有效,但一无所获。为什么会发生这种情况,我该如何解决?下面是代码:

<html>
<head>
<title>Website</title>
<h1 id="txt_1">Value: 0</h1>
<h2 id="txt_2">Increments: 0</h2>
<img src="---" id="img_1" style="width:40px;height:40px;top:1000px;left:100px">
</head>
<body>
<button type="button" onclick="down();"><</button>
<button type="button" onclick="up();">></button>
X<input type="text" id="box_x" value=0></input>
Y<input type="text" id="box_y" value=0></input>
</body>
<footer>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;">
</canvas>
</footer>
<script>
var val = 0;
var add = 0;
function up(){
add++;
updateUI();
}
function down(){
add--;
updateUI();
}
function updateUI(){
document.getElementById("txt_1").innerHTML = "Value: " + val;
document.getElementById("txt_2").innerHTML = "Increments: " + add;
document.getElementById("img_1").style.top = 80 + "px";
}
function update(){
val+=add;
document.getElementById("myCanvas").height = val + 10;
document.getElementById("myCanvas").width = val + 10;
document.getElementById("txt_1").innerHTML = "Value: " + val;
}
setInterval(update,100);
</script>
</html>

我没有看到任何定义的样式或链接到一个。css文件。但是,如果你想移动它,你的图像应该在它的样式中有一个"position:absolute"。

使用

:

<img src="---" id="img_1" style=""position:absolute;width:40px;height:40px;top:1000px;left:100px">

而不是:

<img src="---" id="img_1" style="width:40px;height:40px;top:1000px;left:100px">