ネイティブ JavaScript で DIV ドラッグと繰り返し領域の計算を実装_JavaScript スキル

WBOY
リリース: 2016-05-16 16:22:31
オリジナル
1279 人が閲覧しました

コードをコピー コードは次のとおりです:

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

<スクリプト言語="javascript">
(関数(ウィンドウ,未定義){
window.Sys = function (ua){
    var b = {
        例: /msie/.test(ua) && !/opera/.test(ua),
        オペラ: /opera/.test(ua),
        サファリ: /webkit/.test(ua) && !/chrome/.test(ua),
        Firefox: /firefox/.test(ua),
        クロム: /chrome/.test(ua)
    },vMark = "";
    for (var i in b) {
        if (b[i]) { vMark = "サファリ" == i ? 「バージョン」: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);

window.$ = function(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;
    if(fn){
        for(ハンドラーを入力)
            if(ハンドラー[タイプ]===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 スライス = Array.prototype.slice;
window.Bind = function(object, fun) {
    var args = slide.call(arguments).slice(2);
    return function() {
            return fun.apply(object, args);
    };
};
window.BindAsEventListener = function(object, fun,args) {
    var args = slide.call(arguments).slice(2);
    戻り関数(イベント) {
        return fun.apply(object, [event || window.event].concat(args));
    }
};
//jQからコピー
window.extend = function(){
    var ターゲット = 引数[0] || {}、i = 1、長さ = argument.length、深さ = true、オプション;
    if ( typeof target === "boolean" ) {
        深い = ターゲット;
        ターゲット = 引数[1] || {};
        i = 2;
    }
    if ( typeof target !== "object" && Object.prototype.toString.call(target)!="[オブジェクト関数]")
        ターゲット = {};
    for(;i         if ( (オプション = 引数[ i ]) != null )
            for(オプションの変数名){
                var src = ターゲット[名前]、コピー = オプション[名前];
                if (ターゲット === コピー)
                    続行;
                if ( deep && copy && typeof copy === "object" && !copy.nodeType ){
                    target[ name ] = argument.callee( deep, src || ( copy.length != null ? [ ] : { } ), copy );
                }
                else if(コピー !== 未定義)
                    ターゲット[名前] = コピー;                       
            }
    }
    リターンターゲット。           
};
//jQからコピー
window.each = function ( object, callback, args ) {
    変数名、i = 0、長さ = object.length;  
    if ( args ) {
  args = Array.prototype.slice.call(arguments).slice(2);
        if ( 長さ === 未定義 ) {
            for ( オブジェクト内の名前 )
                if ( callback.apply( object[ name ],[name,object[ name ]].concat(args) ) === false )
                    壊す;  
        } else
            for ( ; i                 if ( callback.apply( object[ i ],[i,object[ i ]].concat(args)) === false ) //
                    壊す;  
    } else {
        if ( 長さ === 未定義 ) {
            for ( オブジェクト内の名前 )
                if ( callback.call( object[ name ], name, object[ name ] ) === false )
                    壊す;  
        } else
            for ( var value = object[0];
                私は<長さ && callback.call( value, i, value ) !== false;値 = オブジェクト[ i] ){}
    }
    オブジェクトを返します。  
};  
window.currentStyle = 関数(要素){
    戻り要素.currentStyle || document.defaultView.getComputedStyle(element, null);
};
window.objPos = function(elem){
    var left = 0、top = 0、right = 0、bottom = 0、doc = elem ? elem.ownerDocument : ドキュメント;
    if ( !elem.getBoundingClientRect || window.Sys.ie8 ) {
        var n = elem;
        while (n) { left = n.offsetLeft、top = n.offsetTop; n = n.offsetParent; };
        右 = 左 elem.offsetWidth;底部 = 上部の elem.offsetHeight;
    } else {
        var rect = elem.getBoundingClientRect();
        左 = 右 = doc.documentElement.scrollLeft || doc.body.scrollLeft;
        上 = 下 = doc.documentElement.scrollLeft || doc.body.scrollLeft;
        左 = 直方体左; right =rect.right;
        トップ = 長方形トップ;ボトム=rect.bottom;
    }
    return { "left": 左、"top": 上、"right": 右、"bottom": 下 };       
};
window.hasClass = function(element, className){
    return element.className.match(new RegExp('(\s|^)' className '(\s|$)'));
};
window.addClass = function(要素, クラス名){
    !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 Drag = {
    要素 : null、
    zindex : 0,
    オプション: {}、
    init : function(){
  each(arguments,function(i,elem,oThis){
    addListener(elem,'mousedown',BindAsEventListener(oThis,oThis.start,elem));
  },これ);
    }、
    開始: function(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(document,"mouseup",Bind(this,this.up)); 
  this.options.callbackmove&&this.options.callbackmove(this.elem);
    }、
    move : function(e){
        window.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);
    }、
    アップ : function(){
        RemoveListener(document,'mousemove');
        RemoveListener(document,'mouseup');
        Sys.ie&&this.elem.releaseCapture();
        this.options.callbackup&&this.options.callbackup(this.elem);
    }
};

var オーバーラップ = {
    hostel :{}, // すべて必要计算重ね的要素
    overlapList :{}, //すでに重ねた元素
    init: function(elems){
        each(elems,function(i,elem,oThis){
            elem.setAttribute('overlap',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:function(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 : function(my){
        var obj= {}, my = this.hostel[my.getAttribute('overlap')];
       
        each(this.hostel,function(key,config,oThis){
            // 是元素本身则返
            if(config.elem === my.elem)return ;
   
            //判断2个divが否か重ねた場合結果不重ね则返し
            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)
                戻る;
            obj[config.elem.getAttribute('overlap')] = [config.elem,oThis.howOverlap(my,config)];
        },これ);
        obj を返します;
    }、
 // 判断重ね面积
    howOverlap : function(my,other){
        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]) 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;
   return Math.abs((x1-x2)*(y1-y2));  
  };   
  //完全重ね
  if(arr.length===4){
   162*162 を返します。 
  };  
    }、
 //看点は不存在です一つの div 内にあります
    インクルード: function(dot,l,r,t,b,key){
  return (dot.x>=l&&dot.x<=r&&dot.y>=t&&dot.y<=b)?key:false;
    }
};
window.onload = function(){
    extend(Drag.options,{callbackmove:move,callbackup:up});
 
    関数 up(elem){
        for(overlap.overlapList の var n)
            RemoveClass(overlap.overlapList[n][0],'focus')
オーバーラップ.overlapList = {};
Drag.elem.innerHTML =Drag.elem.id;
};

関数 move(elem){
overlap.setElem(elem);
//p は、返された obj が空かどうかを判断するために使用されます
var obj =overlap.isOverlap(elem),name,p = function(o){
for (oの名前)
return false;
true を返します;
}(obj);
// 空のオブジェクトの場合は戻り、次の走査は実行しません
if(p){
up();
return;
};

var str =''; オーバーラップ.overlapList = obj;
each(overlap.hostel,function(key,config){
If(obj[キー]){
addClass(obj[key][0],'focus');
str = str 'obj[key][0].id 'と重なる領域は:' obj[key][1] '
';
}その他{
removeClass(config.elem,'focus');
}
});
Drag.elem.innerHTML = str;
};
Drag.init($('demo1'),$('demo2'),$('demo3'),$('demo4'),$('demo5'),$('demo6'),$('demo7 '),$('demo8'),$('demo9'));
オーバーラップ.init([$('demo1'),$('demo2'),$('demo3'),$('demo4'),$('demo5'),$('demo6'),$('デモ7'),$('デモ8'),$('デモ9')]);
};





コードは上記の通りですが、少し効率が悪い気がします。何か最適化計画はありますか? 教えてください。
関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!