日期:2014-05-16  浏览次数:20400 次

javascript 跟踪效果

<!DOCTYPE HTML>
<html>
?<head>
? <title> trails </title>
? <meta name="Generator" content="EditPlus">
? <meta name="Author" content="">
? <meta name="Keywords" content="">
? <meta name="Description" content="">
? <style type="text/css">
? *{margin:0;padding:0;}
? .box{
??? position:absolute;
??? border:1px solid #000;
??? border-radius:5px;
??? color:green;
??? width:10px;
??? height:10px;
??? line-height:3px;
??? text-indent:3px;
??? text-align:center;
? }
? </style>
?</head>

?<body>
??? <div id="box" style="left:100px;top:100px;" class="box">.</div>
??? <div id="box1" style="left:300px;top:400px;" class="box">.</div>
??? <div id="box2" style="left:500px;top:500px;" class="box">.</div>
? <script>
??? function tracker(obj){
??? ??? this.aim = obj.aim || 'mouse'; //目标默认为鼠标
??? ??? this.aimLeft = 0;? //表示当前目标的位置
??? ??? this.aimTop = 0;
??? ??? this.trailsman = obj.trails;? //跟踪者
??? ??? this.trailsLeft = parseInt(this.trailsman.style.left,10); //表示当前跟踪者的位置
??? ??? this.trailsTop = parseInt(this.trailsman.style.top,10);
??? ??? this.setPos = function(){
??? ??? ??? var dis = Math.sqrt(Math.pow((this.aimLeft-this.trailsLeft), 2) + Math.pow((this.aimTop - this.trailsTop), 2)),
??? ??? ??? ??? angleX = (this.aimLeft-this.trailsLeft)/dis,
??? ??? ??? ??? angleY = (this.aimTop - this.trailsTop)/dis,
??? ??? ??? ??? speed = obj.speed || 2,
??? ??? ??? ??? speedX = speed * angleX,
??? ??? ??? ??? speedY = speed * angleY;
??? ??? ??? this.trailsLeft += speedX;
??? ??? ??? this.trailsTop += speedY;
??? ??? ??? this.trailsman.style.left = this.trailsLeft + 'px';
??? ??? ??? this.trailsman.style.top = this.trailsTop + 'px';
??? ??? }
??? ???
??? }
??? var box = document.getElementById('box');
??? var box1 = document.getElementById('box1');
??? var box2 = document.getElementById('box2');
??? var eg = [box,box1,box2];
??? for(var i = 0,j = eg.length;i < j;i++){
??? ??? (function(i){
??? ??? ??? eg[i] = new tracker({
??? ??? ??? ??? trails:eg[i]
??? ??? ??? });
??? ??? ??? if(eg[i].aim == 'mouse'){
??? ??? ??? ??? addEvent(document,"mousemove",function(e){
??? ??? ??? ??? ??? eg[i].aimLeft = getMos(e).x,? //表示当前目标的位置
??? ??? ??? ??? ??? eg[i].aimTop = getMos(e).y;
??? ??? ??? ??? });
??? ??? ??? }
??? ??? ??? setInterval(function(){eg[i].setPos();},10);? //设置跟踪者的位置
??? ??? })(i)
??? ???
??? }
??? function addEvent(obj,type,fn){
??? ??? if(obj.attachEvent){
??? ??? ??? obj.attachEvent("on"+type,fn);
??? ??? }else if(obj.addEventListener){
??? ??? ??? obj.addEventListener(type,fn,false);
??? ??? }
??? }
??? function getMos(e){
??? ??? var x = y = 0,
??? ??? ??? e = e || window.event,
??? ??? ??? doc = document.documentElement || document.body;
??? ??? if(e.pageX){
??? ??? ??? x = e.pageX;
??? ??? ??? y = e.pageY;
??? ??? }else{
??? ??? ??? x = e.clientX + doc.scrollLeft - doc.clientLeft;
??? ??? ??? y = e.clientY + doc.scrollTop - doc.clientTop;
??? ??? }
??? ??? return {x:x,y:y};
??? }
? </script>
?</body>
</html>