拖拽

事件是 dom 交互的主要接口

鼠标事件是重点啊

为了写一个小游戏

我不得不写一个拖拽 以前用jq写过 ,但是 不知怎么地把思路沿用到 原生js里 总会出错 今天又是网友天涯 的指点

也写了一个拖拽 似乎还可以

View Code
 1        (function(){
 2          //简化获取节点
 3          function $(ids){
 4                return document.getElementById(ids);
 5          }
 6          //拖拽函数
 7          function drag(obj){
 8             var o=obj;
 9             function addEvent(el,name,fn){
10               if(el.addEventListener){
11                  el.addEventListener(name,fn,false);
12                   return;
13               }
14              el.attachEvent('on'+name,fn);
15             }
16             function removeEvent(el,name,fn){
17                 if(el.addEventListener){
18                    el.removeEventListener(name,fn,false);
19                     return;
20                 }
21                   el.detachEvent('on'+name,fn);
22 
23             }
24             function move(e){
25                 o.style.left=e.clientX-50+"px";
26                 o.style.top=e.clientY-50+"px";
27                 if(e.preventDefault){
28                     e.preventDefault();
29                 }else{
30                     window.event.returnValue = false;
31                 }
32             }
33             addEvent(o,"mousedown",function(e){
34                 addEvent(document,"mousemove",move)
35             });
36             addEvent(document,"mouseup",function(e){
37                 removeEvent(document,"mousemove",move);
38             });
39        }
40 
41         drag($("mao"));
42         })();

 

<div id="mao" style="cursor:move;background: #00ff00; height: 100px; width: 100px;position: absolute; z-index: 1000;"></div>

 

posted @ 2013-01-09 15:39  技安  阅读(180)  评论(0编辑  收藏  举报