我在 HTML 文件中使用 JavaScript 编写了这段代码,但是当我运行它时,当我更改顶部或左侧时,我拥有的图像不会移动。为什么会发生这种情况,我一直在搜索数小时并复制代码音调以查看它是否有效但没有任何效果。为什么会发生这种情况,我该如何解决? 这是代码:
<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">
关于JavaScript 顶部和左侧位置未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517972/