这个案例的关键点在于HTMLElement元素的style属性——标签对象的所有css属性都是用字符串的形式存储的,如果给出一个数值对象,就会产生bug。尤其是位置属性,必须是加上"px"。
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>JS</title>
<style>
div { background-color: blue;
width: 200px;
height: 200px;
position: absolute; }
</style>
<script src = "script1.js">
</script>
</head>
<body>
<div style = "left:600;"></div>
</body>
</html>
<script>
var div = document.getElementsByTagName("div")[0];
document.onmousemove = function(event){
trail(div, 10, 20, event);
}
</script>
var trail = function(object, x, y, event){
var pos_x = 0;
var pos_y = 0;
// 倒霉的IE
var e = event||window.event;
if(e.pageX||e.pageY){
pos_x = e.pageX;
pos_y = e.pageY;
}
else{
alert("IE!");
}
object.style.position = "absolute";
// 强制类型转换
object.style.top = String((pos_y + y)) + "px";
// 自动类型转换
object.style.left = pos_x + x + "px";
}