ドラッグアンドドロップサンプル(圧縮版)
「ドラッグアンドドロップサンプル - Backstage of theater.js」の圧縮版です。・・・単に書いてみたかっただけです^^;
「こうしたほうがいいよ」的なアドバイスがありましたらコメントくださるとありがたいです。
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 //EN'> <html> <head> <script> /** * 要素ドラッガブル化関数 * id : 対象要素ID */ function makeDraggable(i){var I=parseInt,d=document,w=window,m=[d,'mousemove', function(v){s.left=I(P(v)-a)+'px';s.top=I(P(v,1)-b)+'px';C(v)}],u=[d,'mouseup', function(v){S.apply(w,m);S.apply(w,u);C(v)}],l=d.getElementById(i),s=l.style,p=G ('position'),a=b=0;s.cursor='pointer';if(!p||p=='static'){s.position='relative'; if(w.opera)s.top=s.left='0px'}O(l,'mousedown',function(v){var x=G('left'),y=G( 'top');a=P(v)-((!x||x=='auto')?0:I(x));b=P(v,1)-((!y||y=='auto')?0:I(y));O.apply (w,m);O.apply(w,u);C(v)});function G(n){var r=l.currentStyle;return (r)?r[n]:w. getComputedStyle(l,'').getPropertyValue(n)}function P(v,z){var t=(z)?'Y':'X',o= 'scroll'+((z)?'Top':'Left');return (v['client'+t]+(d.documentElement[o]||d.body[ o]))||v['page'+t]}function C(v){try{v.prevDefault();v.stopPropagation()}catch(e) {v.returnValue=0;v.cancelBubble=1;}}function O(l,n,f){try{l.addEventListener(n,f ,0)}catch(e){try{l.attachEvent('on'+n,f)}catch(e){}}}function S(l,n,f){try{l. removeEventListener(n,f,0)}catch(e){try{l.detachEvent('on'+n,f)}catch(r){}}}} function init(){ makeDraggable('test1'); makeDraggable('test2'); makeDraggable('test3'); } </script> <style> div{border:solid blue 2px;background-color:yellow;} </style> </head> <body onload='init();'> <div id='test1' style='width:300px;height:300px;'>TEST1 <div id='test2' style='width:200px;height:200px;'>TEST2 <div id='test3' style='width:100px;height:100px;'>TEST3 </div></div></div> </body> </html>
【注】DIV要素の(幅OR高さ)AND背景色をつけないと、IEで初回ドロップ後にイベントの有効範囲が文字の部分だけになります。