我不确定为什么我的移动功能,不会改变我的玩具'
的style.left或style.top属性有关如何设置div动画的任何提示或一般信息/链接?我把头发拉到这里。 :)
var ref;
var timer;
var velocity = 50;
var deltaX = 5;
var deltaY = 5;
var left = 0;
var top = 0;
//var moveX = math.random() * velocity;
//var moveY = math.random() * velocity;
function init() {
alert("in init fucntion");
ref = document.getElementById("toy");
alert("ref = " + ref.valueOf());
timer = setInterval(move, 50);
}
function move() {
alert("called move");
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
alert("left = " + left.valueOf() + " top = " + top.valueOf());
left += 5;
top += 5;
alert("left =" + left.valueOf() + "top = " + top.valueOf());
ref.style.left += left;
ref.style.top += 5;
alert("ref.style.left = " + ref.style.left.valueOf() + " ref.style.top = " + ref.style.top.valueOf());
ref.style.left = (left + deltaX) % posEnd;
}
var posEnd = 0;
var objWidth = 100;
if (window.innerWidth) {
posEnd = window.innerWidth
} else if (window.document.body.clientWidth) {
posEnd = window.document.body.clientWidth
}

<body onload="init()">
<div style="width: 100px; height: 100px; position:absolute; left: 0px; top: 0px;" id="toy">
<img src="http://images.all-free-download.com/images/graphiclarge/mouse_clip_art_6054.jpg" style="max-height: 100%; max-width: 100%;">
</div>
&#13;
答案 0 :(得分:2)
您只需指定位置所在的单位。例如,style.left = 10
不起作用 - 您需要style.left = '10px'
;
以下是move()
功能的略微简化版本,显示了以下内容:
function move() {
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
left += 5;
top += 5;
ref.style.left = left + 'px';
ref.style.top = top + 'px';
}
一个完整的代码片段:
var ref;
var timer;
var velocity = 50;
var deltaX = 5;
var deltaY = 5;
var left = 0;
var top = 0;
function init() {
ref = document.getElementById("toy");
timer = setInterval(move, 500);
}
function move() {
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
left += 5;
top += 5;
ref.style.left = left + 'px';
ref.style.top = top + 'px';
}
var posEnd = 0;
var objWidth = 100;
if (window.innerWidth) {
posEnd = window.innerWidth
} else if (window.document.body.clientWidth) {
posEnd = window.document.body.clientWidth
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body onload="init()">
<div style="width: 100px; height: 100px; position:absolute; left: 0px; top: 0px;" id="toy">
<img src="http://images.all-free-download.com/images/graphiclarge/mouse_clip_art_6054.jpg" style="max-height: 100%; max-width: 100%;">
</div>
</body>
</html>