JS运动基础之鼠标小特效
- 盒子跟着鼠标动起来的原始代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#one{
width: 200px;
height: 200px;
background: cyan;
position: absolute;
/*一定要定位,不然下面的top跟left都用不了了*/
}
</style>
<script type="text/javascript">
// window.onload=function(){
document.onmousemove=function(ev){
var iEvent=ev||event;
var oOne=document.getElementById('one');
//加上这句话后才能够移动到哪里都没问题
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
oOne.style.left=iEvent.clientX+'px';
oOne.style.top=iEvent.clientY+'px';
}
// }
</script>
</head>
<body>
<div id="one">
</div>
</body>
</html>
2.接下来是鼠标移动的封装函数
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#one{
width: 200px;
height: 200px;
background: cyan;
position: absolute;
}
</style>
<script type="text/javascript">
//封装函数
function getDom(ev){
//定义屏幕向上滚动的距离
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
//定义屏幕向左边滚动的距离
var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft;
return{x:ev.clientX+scrollLeft,y:ev.clientY+scrollTop};
}
document.onmousemove=function(ev){
var oOne=document.getElementById('one');
var iEvent=ev||event;//事件的兼容性处理
var dom=getDom(iEvent);//调用getDom()函数
// var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;//定义屏幕被卷上去的距离
oOne.style.left=dom.x+'px';
oOne.style.top=dom.y+'px';
}
</script>
</head>
<body>
<div id="one">
</div>
</body>
</html>
3.有了以上的两个步骤呢,下面重点来了:
鼠标的移动小效果(母鸡带小鸡)
调用封装函数后
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
div{
width: 40px;
height: 40px;
border-radius: 20px;
background: cyan;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload=function(){
function getDom(ev){
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft;
return{x:ev.clientX+scrollLeft,y:ev.clientY+scrollTop};
}
document.onmousemove=function(ev){
var iEvent=ev||event;
var dom=getDom(iEvent);
var aDiv=document.getElementsByTagName('div');
//下面来个for循环,让后面的div都跟随前面的div移动
for(var i=aDiv.length-1;i>0;i--){
aDiv[i].style.left=aDiv[i-1].offsetLeft+'px';
aDiv[i].style.top=aDiv[i-1].offsetTop+'px';
}
aDiv[0].style.left=dom.x+'px';
aDiv[0].style.top=dom.y+'px';
}
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
运行结果如图所示: