JavaScript顶部和左侧位置未按预期工作

时间:2015-07-20 11:17:39

标签: javascript html css

我在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>

1 个答案:

答案 0 :(得分:0)

我没有看到任何已定义的样式或指向.css文件的链接。但是,如果你想移动图像,你的图像应该在某个地方有一个“位置:绝对”。

使用此:

<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">