css部分
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>
html
<body style="height: 3000px;">
<div></div>
</body>
js部分
<script type="text/javascript">
var odiv=document.getElementsByTagName('div')[0];
window.onmousemove=function(e){
var h=document.documentElement.scrollTop||document.body.scrollTop;
var e=e||window.event;
var l=e.clientX-odiv.offsetWidth/2;
var t=e.clientY-odiv.offsetHeight/2;
if(l<0){
l=0
}
if(t<0){
t=0;
}
if(l>document.documentElement.clientWidth-odiv.offsetWidth){
l=document.documentElement.clientWidth-odiv.offsetWidth;
}
if(t>document.documentElement.clientHeight-odiv.offsetHeight){
t=document.documentElement.clientHeight-odiv.offsetHeight;
}
odiv.style.left=l+'px';
odiv.style.top=t+h+'px';
}
</script>