javascript - 利用JS修改元素的位置属性,为什么style.left可行而style.top失效?

查看:75
本文介绍了javascript - 利用JS修改元素的位置属性,为什么style.left可行而style.top失效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

Q.想利用JS中的move函数实现小图的斜线下移,但是明明代码几乎一样,left的移动可以实现,top却怎么也动不了

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>台球桌</title>
<style type="text/css">
*{
    padding:0;
    margin:0;
}
div{
    background:url(../PICTURE/table.JPG) no-repeat;
    height:260px;
    width:465px;
}
#ball{}
</style>
<script>
function init(){
    var timer = setInterval("move()",50);    
}
function move(){
    var ball = document.getElementById("ball");
    left = parseInt(ball.style.left);
    left += 1;
    top = parseInt(ball.style.top);
    top += 1;
    ball.style.left = left + "px";
    ball.style.top = top + "px";    
}
</script>
</head>

<body onload="init()">
<div>
<img src="../PICTURE/ball.png" id="ball" style="position:absolute;left:6px;top:5px;"/>
</div>
</body>
</html>

解决方案

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>top</title>
</head>
<body>

<div style="width: 100px;height: 100px;position: absolute;top: 10px;left: 10px;background-color: #1b6d85" id="ball"></div>
<script type="text/javascript">
  function init(){
    setInterval("move()",100);
  }
  function move(){
    var ball = document.getElementById("ball");
    var left = parseInt(ball.style.left);
    left += 1;
    var top = parseInt(ball.style.top);
    top += 1;
    ball.style.left = left + "px";
    ball.style.top = top + "px";
  }
  init();
</script>
</body>
</html>

希望您严格按照W3C标准来写JS代码。

这篇关于javascript - 利用JS修改元素的位置属性,为什么style.left可行而style.top失效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆