首頁 > web前端 > js教程 > 主體

原生javascript實作DIV拖曳並計算重複面積_javascript技巧

WBOY
發布: 2016-05-16 16:22:31
原創
1306 人瀏覽過

複製程式碼 程式碼如下:

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.w3.org/1999/xhtml">


Table



demo1

demo2

demo3

demo4

demo5

demo6

demo7

demo8

demo9


(函數(窗口,未定義){
window.Sys = 函數 (ua){
    var b = {
        即: /msie/.test(ua) && !/opera/.test(ua),
        歌劇:/opera/.test(ua),
        Safari: /webkit/.test(ua) && !/chrome/.test(ua),
        火狐:/firefox/.test(ua),
        鉻:/chrome/.test(ua)
    },vMark = "";
    for (var i in b) {
        if (b[i]) { vMark = "safari" == i ? 「版本」:我;休息; }
    }
    b.version = vMark && RegExp("(?:" vMark ")[\/: ]([\d.] )").test(ua) ? RegExp.$1 : "0";
    b.ie6 = b.ie && parseInt(b.version, 10) == 6;
    b.ie7 = b.ie && parseInt(b.version, 10) == 7;
    b.ie8 = b.ie && parseInt(b.version, 10) == 8;  
    回 b;
}(window.navigator.userAgent.toLowerCase());

window.Sys.ie6&&document.execCommand("BackgroundImageCache", false, true);

視窗.$ = 函數(Id){
    return document.getElementById(Id);
};
window.addListener = function(element,e,fn){
    !element.events&&(element.events = {});
    element.events[e]&&(element.events[e][addListener.guid ]=fn)||(element.events[e] = {'0':fn});
    element.addEventListener?element.addEventListener(e,fn,false):element.attachEvent("on" e,fn);
};
window.addListener.guid = 1;
window.removeListener = function(element,e,fn){
    var handlers = element.events[e],type;
    如果(fn){
        for(輸入處理程序)
            if(handlers[type]===fn){
                element.removeEventListener?element.removeEventListener(e,fn,false):element.detachEvent("on" e,fn);
                移除處理程序[型別];
            }
    }其他{
        for(輸入處理程序){
            element.removeEventListener?element.removeEventListener(e,handlers[type],false):element.detachEvent("on" e,handlers[type]);
            移除處理程序[型別];
        }
    }       
};
window.setStyle = function(e,o){
    if(typeof o=="string")
        e.style.cssText=o;
    否則   
        for(var i in o)
            e.style[i] = o[i];
};

var slice = Array.prototype.slice;
window.Bind = function(object, fun) {
    var args = slice.call(arguments).slice(2);
    回傳函數() {
            return fun.apply(object, args);
    };
};
window.BindAsEventListener = function(object, fun,args) {
    var args = slice.call(arguments).slice(2);
    返回函數(事件){
        return fun.apply(object, [event || window.event].concat(args));
    }
};
//從jQ
複製 window.extend = function(){
    var 目標 = 參數[0] || {}, i = 1, length = argument.length, deep = true, options;
    if ( typeof target === "boolean" ) {
        深度=目標;
        目標=參數[1] || {};
        我 = 2;
    }
    if ( typeof target !== "object" && Object.prototype.toString.call(target)!="[object Function]")
        目標 = {};
    for(;i         if ( (options = argument[ i ]) != null )
            for(選項中的變項名稱){
                var src = target[ name ], copy = options[ name ];
                if ( 目標 === 複製 )
                    續;
                if ( deep && copy && typeof copy === "object" && !copy.nodeType ){
                            地                 }   
                else if(複製!==未定義)
                    目標[姓名]=複製;                           }
    }
    回目標;           
};
//從jQ
複製 window.each = 函數(物件、回呼、參數){  
    var name, i = 0, length = object.length;  
    if ( args ) {
  args = Array.prototype.slice.call(arguments).slice(2);
        if ( 長度 === 未定義 ) {  
            for (物件中的名稱)  
                if (callback.apply( object[ name ],[name,object[ name ]].concat(args) ) === fargalse ) === 發現                     休息;  
        } 其他 
            for ( ; i                 if (callback.apply( object[ i ],[i,object[ i ]].concat(args)) === false )   //
                    休息;  
    } 其他 {     
        if ( 長度 === 未定義 ) {  
            for (物件中的名稱)  
                if (callback.call(物件[姓名],名稱,物件[姓名])=== false)  
                    休息;  
        } 其他 
            for ( var value = object[0];  
                我     }  
    回傳物件;  
};  
window.currentStyle = 函數(元素){
    回傳元素.currentStyle || document.defaultView.getCompulatedStyle(element, null);
};
window.objPos = 函數(elem){
    var 左 = 0,上 = 0,右 = 0,下 = 0,doc = elem ? elem.ownerDocument :文件;
    if ( !elem.getBoundingClientRect || window.Sys.ie8 ) {
        var n = elem;
        while (n) { 左 = n.offsetLeft, 上 = n.offsetTop; n = n.offsetParent; };
        右 = 左 elem.offsetWidth;底部 = 頂部 elem.offsetHeight;
    } 其他 {
        var rect = elem.getBoundingClientRect();
        左 = 右 = doc.documentElement.scrollLeft || doc.body.scrollLeft;
        上方 = 底部 = doc.documentElement.scrollLeft || doc.body.scrollLeft;
        左 = 長方形.左;右 = 直角.右;
        上方 = 長方形.上方;底部 = rect.bottom;
    }
    return { "left": 左, "top": 上, "right": 右, "bottom": 下 };       
};
window.hasClass = function(element, className){
    return element.className.match(new RegExp('(\s|^)' className '(\s|$)'));
};
window.addClass = function(element, className){
    !window.hasClass(element, className)&&(element.className = " " className);
};
window.removeClass = function(element, className){
window.hasClass(element, className)&&(element.className = element.className.replace(new RegExp('(\s|^)' className '(\s|$)'),' ' ));
}
})(視窗);

var 拖曳 = {
    elem   :空,
    zindex:0,
    選項:{},
    初始化    : function(){       
  每個(參數,函數(i,elem,oThis){
    addListener(elem,'mousedown',BindAsEventListener(oThis,oThis.start,elem));
  },這個);
    },
    開始:函數(e,elem){
        var elem=this.elem = elem;
        elem.style.zIndex= this.zindex;
        this.x = e.clientX - elem.offsetLeft ;
        this.y = e.clientY - elem.offsetTop;
        this.marginLeft = parseInt(currentStyle(elem).marginLeft)||0;
        this.marginTop = parseInt(currentStyle(elem).marginTop)||0;
        Sys.ie?elem.setCapture():e.preventDefault();
        addListener(document,"mousemove",BindAsEventListener(this,this.move));
        addListener(文檔,"mouseup",Bind(this,this.up)); 
  this.options.callbackmove&&this.options.callbackmove(this.elem);
    },
    移動:函數(e){
        窗口.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        var iLeft = e.clientX - this.x,iTop = e.clientY - this.y;obj = this.elem;
        obj.style.left = iLeft - this.marginLeft "px";
        obj.style.top = iTop - this.marginTop "px";
        this.options.callbackmove&&this.options.callbackmove(this.elem);
    },
    向上:函數(){
        removeListener(document,'mousemove');
        removeListener(document,'mouseup');
        Sys.ie&&this.elem.releaseCapture();
        this.options.callbackup&&this.options.callbackup(this.elem);
    }
};

var 重疊 = {
    宿舍 :{},                //所有需要計算重疊的元素
    overlapList :{},           // 已重疊的元素
    初始化:函數(elems){
        各(elems,函數(i,elem,oThis){
            elem.setAttribute('重疊),i);
            var ret = objPos(elem),l=ret.left,t=ret.top,b=ret.bottom,r=ret.right;
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}};
        },這個);
    },
    setElem:函數(elem){
        if(!elem)return;
        var ret = objPos(elem),l=ret.left,t=ret.top,b=ret.bottom,r=ret.right;
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}};
    },
 //判斷是否重疊    
    isOverlap : 函數(我的){
        var obj= {}, my = this.hostel[my.getAttribute('overlap')];
       
        各(this.hostel,function(key,config,oThis){
            // 是元素本身則回傳
            if(config.elem === my.elem)return ;
   
            //判斷2個div是否重疊則回復
if(my.leftBottomDot.y=config.leftBottomDot.y||my.rightTopDot.x =config.rightTopDot.x)
                返回;
            obj[config.elem.getAttribute('overlap')] = [config.elem,oThis.howOverlap(my,config)];
        },這個);
        返回物件;
    },
 //判斷重疊面積
    howOverlap :函數(我的,其他){
        var l=other.leftBottomDot.x,r=other.rightTopDot.x,t=other.leftTopDot.y,b=other.leftBottomDot.y,arr=[],
        lt = this.include(my.leftTopDot,l,r,t,b,'leftTopDot-rightBottomDot'),
        lb = this.include(my.leftBottomDot,l,r,t,b,'leftBottomDot-rightTopDot'),
        rt = this.include(my.rightTopDot,l,r,t,b,'rightTopDot-leftBottomDot'),
        rb = this.include(my.rightBottomDot,l,r,t,b,'rightBottomDot-leftTopDot');
        lt&&arr.push(lt)||lb&&arr.push(lb)||rt&&arr.push(rt)||rb&&arr.push(rb);
       
        if(!arr[0]) return 0;
  
  if(arr.length====1||arr.length====2){
var key = arr[0].split('-'),x1=my[key[0]].x,y1=my[key[0]].y,x2=other[key[1]].x ,y2=其他[鍵[1]].y;
   返回 Math.abs((x1-x2)*(y1-y2));  
  };   
  //完全重疊
  if(arr.length===4){
   返回162*162; 
  };  
    },
 // 看點不是在另一個div中
    包括:函數(點,l,r,t,b,鍵){
  return (dot.x>=l&&dot.x=t&&dot.y     }
};
window.onload = function(){
    擴充(Drag.options,{callbackmove:move,callbackup:up});
 
    函數向上(elem){
        for(重疊中的 var n.overlapList)
            removeClass(overlap.overlapList[n][0],'focus')
        overlap.overlapList = {};
        Drag.elem.innerHTML =Drag.elem.id;
    };
 
    function move(elem){
        overlap.setElem(elem);
        //p為判斷回傳的obj是不是空的
        var obj = overlap.isOverlap(elem),name,p = function(o){
            for (name in o)
                return 稱為;
            return true;
        }(obj);   
       
        //如果為空物件 則回傳 不進行下面的遍歷
        if(p){
            up();
            return;
        };
       
        var str ='';       
        overlap.overlapList = obj;
        each(overlap.hostel,function(key,config){
            if(obj[key]){
                addClass(obj[key][0],'focus');
    str = str '與' obj[key][0].id '重疊的面積為:' obj[key][1] '';
            }else{
                removeClass(config.elem,'focus');
            }
        });
        Drag.elem.innerHTML = str;
    };
Drag.init($('demo1'),$('demo2'),$('demo3'),$('demo4'),$('demo5'),$('demo6'),$('demo7 '),$('demo8'),$('demo9'));
overlap.init([$('demo1'),$('demo2'),$('demo3'),$('demo4'),$('demo5'),$('demo6'),$(' demo7'),$('demo8'),$('demo9')]);
};

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板