원본 자바스크립트 DIV 드래그 및 중복 면적 계산

15908 단어
 
  




Table



demo1

demo2

demo3

demo4

demo5

demo6

demo7

demo8

demo9

<br> (function(window,undefined){ <br> window.Sys = function (ua){ <br>     var b = { <br>         ie: /msie/.test(ua) && !/opera/.test(ua), <br>         opera: /opera/.test(ua), <br>         safari: /webkit/.test(ua) && !/chrome/.test(ua), <br>         firefox: /firefox/.test(ua), <br>         chrome: /chrome/.test(ua) <br>     },vMark = ""; <br>     for (var i in b) { <br>         if (b[i]) { vMark = "safari" == i ? "version" : i; break; } <br>     } <br>     b.version = vMark && RegExp("(?:" + vMark + ")[\\/: ]([\\d.]+)").test(ua) ? RegExp.$1 : "0"; <br>     b.ie6 = b.ie && parseInt(b.version, 10) == 6; <br>     b.ie7 = b.ie && parseInt(b.version, 10) == 7; <br>     b.ie8 = b.ie && parseInt(b.version, 10) == 8;   <br>     return b; <br> }(window.navigator.userAgent.toLowerCase()); <p></p> <p>window.Sys.ie6&&document.execCommand("BackgroundImageCache", false, true);</p> <p>window.$ = function(Id){<br>     return document.getElementById(Id);<br> };<br> window.addListener = function(element,e,fn){<br>     !element.events&&(element.events = {});<br>     element.events[e]&&(element.events[e][addListener.guid++]=fn)||(element.events[e] = {'0':fn});<br>     element.addEventListener?element.addEventListener(e,fn,false):element.attachEvent("on" + e,fn);<br> };<br> window.addListener.guid = 1;<br> window.removeListener = function(element,e,fn){<br>     var handlers = element.events[e],type;<br>     if(fn){<br>         for(type in handlers)<br>             if(handlers[type]===fn){<br>                 element.removeEventListener?element.removeEventListener(e,fn,false):element.detachEvent("on" + e,fn);<br>                 delete handlers[type];<br>             }<br>     }else{<br>         for(type in handlers){<br>             element.removeEventListener?element.removeEventListener(e,handlers[type],false):element.detachEvent("on" + e,handlers[type]);<br>             delete handlers[type];<br>         }<br>     }        <br> };<br> window.setStyle = function(e,o){<br>     if(typeof o=="string")<br>         e.style.cssText=o;<br>     else    <br>         for(var i in o)<br>             e.style[i] = o[i];<br> };</p> <p>var slice = Array.prototype.slice; <br> window.Bind = function(object, fun) {<br>     var args = slice.call(arguments).slice(2);<br>     return function() {<br>             return fun.apply(object, args);<br>     };<br> };<br> window.BindAsEventListener = function(object, fun,args) {<br>     var args = slice.call(arguments).slice(2);<br>     return function(event) {<br>         return fun.apply(object, [event || window.event].concat(args));<br>     }<br> };<br> //copy from jQ<br> window.extend = function(){<br>     var target = arguments[0] || {}, i = 1, length = arguments.length, deep = true, options;<br>     if ( typeof target === "boolean" ) {<br>         deep = target;<br>         target = arguments[1] || {};<br>         i = 2;<br>     }<br>     if ( typeof target !== "object" && Object.prototype.toString.call(target)!="[object Function]")<br>         target = {};<br>     for(;i<length;i++){<br>         if ( (options = arguments[ i ]) != null )<br>             for(var name in options){<br>                 var src = target[ name ], copy = options[ name ];<br>                 if ( target === copy )<br>                     continue;<br>                 if ( deep && copy && typeof copy === "object" && !copy.nodeType ){<br>                     target[ name ] = arguments.callee( deep, src || ( copy.length != null ? [ ] : { } ), copy );<br>                 }    <br>                 else if(copy !== undefined)<br>                     target[ name ] = copy;                        <br>             }<br>     }<br>     return target;            <br> };<br> //copy from jQ<br> window.each =  function ( object, callback, args ) {   <br>     var name, i = 0, length = object.length;   <br>     if ( args ) {<br>   args = Array.prototype.slice.call(arguments).slice(2);<br>         if ( length === undefined ) {   <br>             for ( name in object )   <br>                 if ( callback.apply( object[ name ],[name,object[ name ]].concat(args) ) === false )   <br>                     break;   <br>         } else  <br>             for ( ; i < length; i++)   <br>                 if ( callback.apply( object[ i ],[i,object[ i ]].concat(args)) === false )   //<br>                     break;   <br>     } else {      <br>         if ( length === undefined ) {   <br>             for ( name in object )   <br>                 if ( callback.call( object[ name ], name, object[ name ] ) === false )   <br>                     break;   <br>         } else  <br>             for ( var value = object[0];   <br>                 i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}   <br>     }   <br>     return object;   <br> };   <br> window.currentStyle = function(element){<br>     return element.currentStyle || document.defaultView.getComputedStyle(element, null);<br> };<br> window.objPos = function(elem){<br>     var left = 0, top = 0, right = 0, bottom = 0,doc = elem ? elem.ownerDocument : document;<br>     if ( !elem.getBoundingClientRect || window.Sys.ie8 ) {<br>         var n = elem;<br>         while (n) { left += n.offsetLeft, top += n.offsetTop; n = n.offsetParent; };<br>         right = left + elem.offsetWidth; bottom = top + elem.offsetHeight;<br>     } else {<br>         var rect = elem.getBoundingClientRect();<br>         left = right = doc.documentElement.scrollLeft || doc.body.scrollLeft;<br>         top = bottom = doc.documentElement.scrollLeft || doc.body.scrollLeft;<br>         left += rect.left; right += rect.right;<br>         top += rect.top; bottom += rect.bottom;<br>     }<br>     return { "left": left, "top": top, "right": right, "bottom": bottom };        <br> };<br> window.hasClass = function(element, className){<br>     return element.className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'));<br> };<br> window.addClass = function(element, className){<br>     !window.hasClass(element, className)&&(element.className += " "+className);<br> };<br> window.removeClass = function(element, className){<br>     window.hasClass(element, className)&&(element.className = element.className.replace(new RegExp('(\\s|^)'+className+'(\\s|$)'),' '));<br> }<br> })(window);</p> <p>var Drag = {<br>     elem    : null,<br>     zindex  : 0,<br>     options : {},<br>     init    : function(){        <br>   each(arguments,function(i,elem,oThis){<br>     addListener(elem,'mousedown',BindAsEventListener(oThis,oThis.start,elem));<br>   },this);<br>     },<br>     start : function(e,elem){<br>         var elem=this.elem = elem;<br>         elem.style.zIndex=++this.zindex;<br>         this.x = e.clientX - elem.offsetLeft ;<br>         this.y = e.clientY - elem.offsetTop;<br>         this.marginLeft = parseInt(currentStyle(elem).marginLeft)||0;<br>         this.marginTop  = parseInt(currentStyle(elem).marginTop)||0;<br>         Sys.ie?elem.setCapture():e.preventDefault();<br>         addListener(document,"mousemove",BindAsEventListener(this,this.move));<br>         addListener(document,"mouseup",Bind(this,this.up));  <br>   this.options.callbackmove&&this.options.callbackmove(this.elem);<br>     },<br>     move  : function(e){<br>         window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();<br>         var iLeft = e.clientX - this.x,iTop = e.clientY - this.y;obj = this.elem;<br>         obj.style.left = iLeft - this.marginLeft + "px";<br>         obj.style.top  = iTop - this.marginTop + "px";<br>         this.options.callbackmove&&this.options.callbackmove(this.elem);<br>     },<br>     up   : function(){<br>         removeListener(document,'mousemove');<br>         removeListener(document,'mouseup');<br>         Sys.ie&&this.elem.releaseCapture();<br>         this.options.callbackup&&this.options.callbackup(this.elem);<br>     }<br> };</p> <p>var overlap = {<br>     hostel :{},                // <br>     overlapList :{},           // <br>     init : function(elems){<br>         each(elems,function(i,elem,oThis){<br>             elem.setAttribute('overlap',i);<br>             var ret = objPos(elem),l=ret.left,t=ret.top,b=ret.bottom,r=ret.right;<br>             oThis.hostel[i]={elem:elem,leftTopDot:{x:l,y:t},leftBottomDot:{x:l,y:b},rightTopDot:{x:r,y:t},rightBottomDot:{x:r,y:b}};<br>         },this);<br>     },<br>     setElem:function(elem){<br>         if(!elem)return;<br>         var ret = objPos(elem),l=ret.left,t=ret.top,b=ret.bottom,r=ret.right;<br>         this.hostel[elem.getAttribute('overlap')] ={elem:elem,leftTopDot:{x:l,y:t},leftBottomDot:{x:l,y:b},rightTopDot:{x:r,y:t},rightBottomDot:{x:r,y:b}};<br>     },<br>  //      <br>     isOverlap : function(my){<br>         var obj= {}, my = this.hostel[my.getAttribute('overlap')];<br>         <br>         each(this.hostel,function(key,config,oThis){<br>             // <br>             if(config.elem === my.elem)return ;<br>    <br>             // 2 div <br>             if(my.leftBottomDot.y<=config.leftTopDot.y||my.leftTopDot.y>=config.leftBottomDot.y||my.rightTopDot.x<=config.leftTopDot.x||my.leftTopDot.x>=config.rightTopDot.x)<br>                 return;<br>             obj[config.elem.getAttribute('overlap')] =[config.elem,oThis.howOverlap(my,config)];<br>         },this);<br>         return obj;<br>     },<br>  // <br>     howOverlap : function(my,other){<br>         var l=other.leftBottomDot.x,r=other.rightTopDot.x,t=other.leftTopDot.y,b=other.leftBottomDot.y,arr=[],<br>         lt = this.include(my.leftTopDot,l,r,t,b,'leftTopDot-rightBottomDot'),<br>         lb = this.include(my.leftBottomDot,l,r,t,b,'leftBottomDot-rightTopDot'),<br>         rt = this.include(my.rightTopDot,l,r,t,b,'rightTopDot-leftBottomDot'),<br>         rb = this.include(my.rightBottomDot,l,r,t,b,'rightBottomDot-leftTopDot');<br>         lt&&arr.push(lt)||lb&&arr.push(lb)||rt&&arr.push(rt)||rb&&arr.push(rb);<br>         <br>         if(!arr[0]) return 0;<br>   // 2   <br>   if(arr.length===1||arr.length===2){<br>    var key = arr[0].split('-'),x1=my[key[0]].x,y1=my[key[0]].y,x2=other[key[1]].x,y2=other[key[1]].y;<br>    return Math.abs((x1-x2)*(y1-y2));  <br>   };   <br>   // <br>   if(arr.length===4){<br>    return 162*162; <br>   };  <br>     },<br>  // div <br>     include : function(dot,l,r,t,b,key){<br>   return (dot.x>=l&&dot.x<=r&&dot.y>=t&&dot.y<=b)?key:false;<br>     }<br> };<br> window.onload = function(){<br>     extend(Drag.options,{callbackmove:move,callbackup:up});<br>  <br>     function up(elem){<br>         for(var n in overlap.overlapList)<br>             removeClass(overlap.overlapList[n][0],'focus')<br>         overlap.overlapList = {};<br>         Drag.elem.innerHTML =Drag.elem.id;<br>     };<br>  <br>     function move(elem){<br>         overlap.setElem(elem);<br>         //p obj <br>         var obj = overlap.isOverlap(elem),name,p = function(o){<br>             for (name in o)<br>                 return false;<br>             return true;<br>         }(obj);    <br>         <br>         // <br>         if(p){<br>             up();<br>             return;<br>         };<br>         <br>         var str ='';        <br>         overlap.overlapList = obj;<br>         each(overlap.hostel,function(key,config){<br>             if(obj[key]){<br>                 addClass(obj[key][0],'focus');<br>     str = str +' '+obj[key][0].id+' :'+obj[key][1]+'</br>';<br>             }else{<br>                 removeClass(config.elem,'focus');<br>             }<br>         });<br>         Drag.elem.innerHTML = str;<br>     };<br>     Drag.init($('demo1'),$('demo2'),$('demo3'),$('demo4'),$('demo5'),$('demo6'),$('demo7'),$('demo8'),$('demo9'));<br>     overlap.init([$('demo1'),$('demo2'),$('demo3'),$('demo4'),$('demo5'),$('demo6'),$('demo7'),$('demo8'),$('demo9')]);<br> };<br>



코드는 위와 같습니다. 다만 효율이 좀 낮은 것 같습니다. 어린 친구들은 최적화 방안이 있습니까? 알려 주십시오. 감격해 마지 않습니다

좋은 웹페이지 즐겨찾기