以前只是看别人写的鼠标跟随效果,感觉挺好玩,今天自己来了一个,兼容FF/IE哦 !!
Copy请用下面textarea中的代码。
<!
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"
xml:lang
="en"
lang
="en"
>
<
head
>
<
title
></
title
>
<
style
type
="text/css"
>
#level
{
border
:
1px solid #ccc
;
background
:
#CCFFCC
;
width
:
100px
;
height
:
30px
;
position
:
absolute
;
}
</
style
>
<
script
type
="text/javascript"
>
function
addEvent(elm, evType, fn, useCapture)
{
if
(elm.addEventListener){
elm.addEventListener(evType, fn, useCapture);
return
true
;
}
else
if
(elm.attachEvent){
var
r
=
elm.attachEvent(
"
on
"
+
evType, fn);
return
r;
}
else
{
alert(
"
Handler could not be removed
"
);
}
}
var
x,y,t;
function
doit(evt){
var
event
=
evt
||
window.event;
var
level
=
document.getElementById(
"
level
"
);
/*
如果是第一次调用该函数level.style.left和level.style.top都为空,所以要初始化
*/
if
(
!
level.style.left)level.style.left
=
"
1px
"
;
if
(
!
level.style.top)level.style.top
=
"
1px
"
;
//
用setTimeout函数调用该函数时event对象不存在,只有移动事件触发时event才存在
if
(event){x
=
(event.x
||
event.pageX)};
if
(event){y
=
(event.y
||
event.pageY)};
var
theLeft
=
parseInt(level.style.left);
var
theTop
=
parseInt(level.style.top);
if
(x
!=
theLeft){
if
(theLeft
<
x){
level.style.left
=
(theLeft
+
1
)
+
"
px
"
;
}
else
{
level.style.left
=
(theLeft
-
1
)
+
"
px
"
;
}
}
if
(theTop
!=
y){
if
(theTop
<
y){
level.style.top
=
(theTop
+
1
)
+
"
px
"
;
}
else
{
level.style.top
=
(theTop
-
1
)
+
"
px
"
;
}
}
if
(x
!=
theLeft
||
y
!=
theTop)
setTimeout(
"
doit()
"
,
100
);
}
addEvent(document,
"
mousemove
"
,doit);
</
script
>
</
head
>
<
body
>
<
div
id
="level"
>
content
</
div
>
</
body
>
</
html
>