[zt]JavaScriptでのドラッグ&ドロップはどうやって実現しますか?


リンク:http://www.webreference.com/programming/javascript/mk/column2/index.html翻訳文リンク:http://www.blogjava.net/flyingis/archive/2006/10/11/74591.html
JavaScriptはページ中のDOM元素を修正するのが得意ですが、JavaScriptを使って、通常はいくつかの簡単な機能を実現します。この記事はどのようにページで作成された要素をドラッグ&ドロップするかを示します。多くの理由で、ページにドラッグ&ドロップ機能を追加することができます。一番簡単な理由はデータの再組織です。一例を挙げると、ユーザーが一連のページ要素を再構築することを望むかもしれません。inputまたはselectコンポーネントを配置することによって、それぞれの要素の隣にそれらを表す順序は解決策であり、このグループの要素をドラッグ&ドロップすることができるようにするのは代替案です。あるいは、ユーザーによって移動できるナビゲーションウィンドウをウェブサイト上に持ちたいかもしれません。これらはすべてドラッグ&ドロップ機能を使う簡単な理由です。あなたが実現できるからです。あなたのホームページでドラッグ&ドロップの効果を実現するのは複雑ではありません。まず、マウスの位置を知っています。そして、ユーザーがいつ元素をクリックしたらいいのかを知る必要があります。ドラッグを開始する準備ができると知っています。最後にこの要素を移動します。マウスをキャプチャする移動の最初のステップは、マウスの座標を取得する必要があります。関数を通してdocument.onmousemooveに与えられます。
document.onmousemove = mouseMove;
function mouseMove(ev) {
  ev = ev || window.event;
  var mousePos = mouseCoords(ev);
}
function mouseCoords(ev) {
  if(ev.pageX || ev.pageY) {
    return {x:ev.pageX, y:ev.pageY};
  }
  return {
    x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
    y:ev.clientY + document.body.scrollTop - document.body.clientTop
  };
}
まず、イベントの対象を説明します。いつ移動しても、マウスをクリックしても、ボタンを押しても、一つのイベントが発生します。IEでは、このイベントはグローバルであり、これはwindow.eventに格納され、Firefoxおよび他のブラウザにとって、このイベントは、このページ動作を指す任意の関数に伝達される。したがって、document.onmousemooveをマウス移動の関数に向け、マウス移動の関数でイベントオブジェクトを取得します。上記のコードには、evはすべてのブラウザ環境において、イベントオブジェクトを含んでいます。Firefoxでは、イベントが含まれているので、「ウィンドウズ.event」は無視されます。IEでは、evの値は空であり、その値をwindow.eventに設定する必要がある。本論文ではマウスの座標を複数回取り込む必要があるので、mouse Coords法を書きました。パラメータ:eventがあります。私たちはIEと他のブラウザとの違いを再度議論したいです。Firefoxおよび他のブラウザは、event.pageXおよびevent.pageYを使用して、document文書に対するマウスの位置を表しています。500*500のウィンドウがあり、マウスがウィンドウの真ん中にあると、PageXとPageYの値は250になります。もしあなたが窓を下に500ピクセルスクロールしたら、PageYの値は750です。これに対して、マイクロソフトのIEは、現在のdocument文書ではなく、event.client Yとevent.clientを使用して、windowウィンドウに対するマウスの位置を表している。同じ例では、マウスを500*500ウィンドウの中間に置くと、clientXとclientYの値は共に250になる。下にページをスクロールすると、clientYはまだ250です。これはwindowウィンドウに対して測定されるので、現在のdocument文書ではありません。したがって、マウスの位置では、document文書body領域のscrollLeftとscrollTopのプロパティを導入する必要があります。最後に、IEの中のdocument文書は実際には(0,0)の位置ではなく、その周囲に小さい(通常は2 pxがある)フレームがあり、Dcument.body.client Leftとdocument.body.clientTopはこのフレームの幅を含んでいます。マウスの位置にそれらを導入する必要があります。幸いにも、今はmouse Coords関数を持っています。マウスの位置を取るために心配しなくてもいいです。マウスをキャプチャして次のステップをクリックすると、マウスがいつクリックされますか?このステップをスキップすると、これらの要素をマウスで移動すると、これらの要素をドラッグする効果があります。これは人の直感に反して嫌いです。ここでは、2つの関数があります。私たちを助けてくれます。onmousedownとonmouseup。以前はdocument.onmousemooveを関数に指していましたので、論理的にはdocument.onmousedownとdocument.onmouseupの両方を関数に指すべきです。もし私たちがdocument.onmousedownに関数を指し示したら、この関数はマウスがどんな要素をクリックしても実行されます。テキスト、画像、表など。ページ内の特定の要素だけをドラッグ&ドロップする機能があると考えています。
document.onmouseup = mouseUp;
var dragObject = null;
function makeClickable(object) {
object.onmousedown = function() {
dragObject = this;
}
}
function mouseUp(ev) {
dragObject = null;

}
私たちは今変数dragObjectを持っています。あなたがクリックしたすべての要素が含まれています。マウスを放したとき、ドラゴObjectは空に設定されています。ドラゴObjectが空でないときはドラッグ操作が必要です。モバイル要素はマウスの動きとクリックをキャプチャする方法が分かりました。次に必要なのはドラッグしたい要素を移動することです。まず、ページ上の要素を正確に移動します。この要素スタイルテーブルのposition値はabsoluteでなければなりません。これはstyle.topまたはstyle.leftを設定することができます。測定値はページの左上隅に対してあります。マウスの移動はすべてページの左上隅に対して行われます。一旦item.style.position='absolute'を設定したら、次に要素topとleftの位置を変えて移動します。
document.onmousemove = mouseMove;
document.onmouseup = mouseUp;
var dragObject = null ;
var mouseOffset = null ;
function getMouseOffset(target, ev) {
ev = ev || window.event;
var docPos = getPosition(target);
var mousePos = mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y} ;
}

function getPosition(e) {
var left = 0;
var top = 0;
while (e.offsetParent) {
left += e.offsetLeft;
top += e.offsetTop;
e = e.offsetParent;
}
left += e.offsetLeft;
top += e.offsetTop;
return {x:left, y:top} ;
}

function mouseMove(ev) {
ev = ev || window.event;
var mousePos = mouseCoords(ev);
if (dragObject) {
dragObject.style.position = 'absolute';
dragObject.style.top = mousePos.y - mouseOffset.y;
dragObject.style.left = mousePos.x - mouseOffset.x;
return false ;
}
}

function mouseUp() {
dragObject = null ;
}

function makeDraggable(item) {
if (!item) return ;
item.onmousedown = function (ev) {
dragObject = this ;
mouseOffset = getMouseOffset(this, ev);
return false ;
}
}
これらのコードは前の例をもとにしています。(前の記事を参照してください。)それらを一緒に置いて、要素を自由に移動することができます。要素をクリックすると、もう一つの変数が格納されます。mouseOffset。mouseOffsetは簡単に元素をクリックする位置情報を含んでいます。もし20*20 pxの画像があったら、画像の真ん中をクリックしてください。mouseOffsetは{x:10,y:10}であるべきです。画像の左上をクリックすると、mouseOffsetは{x:0,y:0}です。私たちはマウスを移動した後の位置情報に使います。この値を保存していない場合は、元素の位置をクリックしても、マウスに対して元素の位置は同じです。mouseOffset関数は他の関数get Positionを使用しています。get Positionは、documemtドキュメントに対する要素の座標位置を返します。私たちが簡単にitem.offset Leftまたはitem.style.leftを読み込むと、documentドキュメントではなく、その親要素に対する要素の位置が得られます。私たちの脚本には、すべての要素が対応していますので、このようにしてください。documentドキュメントの位置に対する要素を取得する作業を完了するには、getPositionは、自身の親レベルから、そのleftとtopの値を循環的に取得して累積します。これにより、ドキュメントの上部と左側からの要素の積算値が得られます。この情報を取得してマウスを移動すると、mousemoveが起動します。まず、私たちはitem.style.positionの値がabsoluteであることを保証します。次に、元素をどこに移動しても、マウスの位置から前に記録したマウスの元素に対するオフセットが差し引かれます。マウスをリリースすると、ドラゴObjectはnullに設定され、mouse Move関数は何もしなくなります。前の例では、要素をドラッグして置くだけです。そして、私たちが元素を置く時には他の目的があります。元素をゴミ回収ステーションにドラッグすることを例にとって、あるいは元素とページの中の特定のエリアを揃えるようにしたいかもしれません。不幸なことに、私たちはここで比較的主要な問題に入りました。私たちが移動している要素はいつも私たちのマウスの下にありますので、mouseover、mousedown、mouseupまたはマウスのページ内の他の要素の操作を誘発することはできません。もしあなたがゴミ回収ステーションに元素を移動したら、マウスはずっと移動元素の上にあります。ゴミ回収ステーションではありません。この問題をどう処理すればいいですか?ここにはいくつかの解決策があります。前に述べたmouseOffsetの目的は元素がいつもマウスの下の正しい位置にあることを保証することです。これを無視すれば、いつもマウスの右下の元素になります。マウスはあなたのドラッグしている要素に隠れられなくなります。問題にも触れません。しかし、実際にはそうではありません。美しいためには、マウスの下にある元素を維持します。もう一つの選択はドラッグしている要素を移動しないことです。マウスのスタイルを変えて、ユーザーにドラッグして要素をどこかに置くまで教えます。これは私たちの問題を解決しましたが、前の案と同じ問題をもたらしました。美しいです。私たちの最後の解決策はあなたが移動している要素にも影響しないし、移動終点の位置にある要素(例えばゴミ回収ステーション)にも影響しません。残念なことに、前の2つの解決策よりも難しいです。私たちが行うのは、ターゲットのセットを取得することです。マウスをリリースする時、現在のマウスの位置を確認します。マウスがこのターゲットの中にあるターゲットの位置に放出されているかどうかを確認します。
/**/ /*
All code from the previous example is needed with the exception
of the mouseUp function which is replaced below
*/

var dropTargets = [];

function addDropTarget(dropTarget) {
dropTargets.push(dropTarget);
}

function mouseUp(ev) {
ev = ev || window.event;
var mousePos = mouseCoords(ev);

for (var i = 0; i < dropTargets.length; i ++) {
var curTarget = dropTargets[i];
var targPos = getPosition(curTarget);
var targWidth = parseInt(curTarget.offsetWidth);
var targHeight = parseInt(curTarget.offsetHeight);

if (
(mousePos.x > targPos.x) &&
(mousePos. < (targPos.x + targWidth)) &&
(mousePos.y > targPos.y) &&
(mousePos.y < (targPos.y + targHeight))) {
// dragObject was dropped onto curTarget!
}
}
dragObject = null ;




, 。 DOM , , 《JavaScript Primer on DOM Manipulation 》。



, , demo 。 , , 。



, 。




1. , dragHelper DIV , ,dragHelper
, 。 , insertBefore appendChild 。
dragHelper。



2. mouseDown mouseUp 。 , , iMouseDown true, false。




3. DragDrops, CreateDragContainer。DragDrops 。
CreateDragContainer ( ) , 。
setAttribute,CreateDragContainer 。



4. , mouseMove 。mouseMove target, , ( getAttribute ) :



4.1. , , class , 。



4.2. ( ), :



4.2.1. curTarget 。

4.2.2. , 。

4.2.3. dragHelper, 。

4.2.4. dragHelper , , dragObj , dragObj 。

4.2.5. 、 。 , , , 。



4.3. , , , 。



5. curTarget 。curTarget , , :



5.1. DIV , 。



5.2. 。



5.2.1. , , 。

5.2.2. , 。

5.2.3. 。



6. mouseUp :

6.1. dragHelper: , 。

6.2. , , 。

6.3. , 。



// iMouseDown represents the current mouse button state: up or down
/**//*
lMouseState represents the previous mouse button state so that we can
check for button clicks and button releases:

if(iMouseDown && !lMouseState) // button just clicked!
if(!iMouseDown && lMouseState) // button just released!
*/
var mouseOffset = null;
var iMouseDown = false;
var lMouseState = false;
var dragObject = null;

// Demo 0 variables
var DragDrops = [];
var curTarget = null;
var lastTarget = null;
var dragHelper = null;
var tempDiv = null;
var rootParent = null;
var rootSibling = null;

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

function CreateDragContainer(){
/**//*
Create a new "Container Instance" so that items from one "Set" can not
be dragged into items from another "Set"
*/
var cDrag = DragDrops.length;
DragDrops[cDrag] = [];

/**//*
Each item passed to this function should be a "container". Store each
of these items in our current container
*/
for(var i=0; i<arguments.length; i++){
var cObj = arguments[i];
DragDrops[cDrag].push(cObj);
cObj.setAttribute('DropObj', cDrag);

/**//*
Every top level item in these containers should be draggable. Do this
by setting the DragObj attribute on each item and then later checking
this attribute in the mouseMove function
*/
for(var j=0; j<cObj.childNodes.length; j++){

// Firefox puts in lots of #text nodesskip these
if(cObj.childNodes[j].nodeName=='#text') continue;

cObj.childNodes[j].setAttribute('DragObj', cDrag);
}
}
}

function mouseMove(ev){
ev = ev || window.event;

/**//*
We are setting target to whatever item the mouse is currently on
Firefox uses event.target here, MSIE uses event.srcElement
*/
var target = ev.target || ev.srcElement;
var mousePos = mouseCoords(ev);

// mouseOut event - fires if the item the mouse is on has changed
if(lastTarget && (target!==lastTarget)){
// reset the classname for the target element
var origClass = lastTarget.getAttribute('origClass');
if(origClass) lastTarget.className = origClass;
}

/**//*
dragObj is the grouping our item is in (set from the createDragContainer function).
if the item is not in a grouping we ignore it since it can't be dragged with this
script.
*/
var dragObj = target.getAttribute('DragObj');

// if the mouse was moved over an element that is draggable
if(dragObj!=null){
// mouseOver event - Change the item's class if necessary
if(target!=lastTarget){
var oClass = target.getAttribute('overClass');
if(oClass){
target.setAttribute('origClass', target.className);
target.className = oClass;
}
}

// if the user is just starting to drag the element
if(iMouseDown && !lMouseState){
// mouseDown target
curTarget = target;

// Record the mouse x and y offset for the element
rootParent = curTarget.parentNode;
rootSibling = curTarget.nextSibling;

mouseOffset = getMouseOffset(target, ev);

// We remove anything that is in our dragHelper DIV so we can put a new item in it.
for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);

// Make a copy of the current item and put it in our drag helper.
dragHelper.appendChild(curTarget.cloneNode(true));
dragHelper.style.display = 'block';

// set the class on our helper DIV if necessary
var dragClass = curTarget.getAttribute('dragClass');
if(dragClass){
dragHelper.firstChild.className = dragClass;
}

// disable dragging from our helper DIV (it's already being dragged)
dragHelper.firstChild.removeAttribute('DragObj');

/**//*
Record the current position of all drag/drop targets related
to the element. We do this here so that we do not have to do
it on the general mouse move event which fires when the mouse
moves even 1 pixel. If we don't do this here the script
would run much slower.
*/
var dragConts = DragDrops[dragObj];

/**//*
first record the width/height of our drag item. Then hide it since
it is going to (potentially) be moved out of its parent.
*/
curTarget.setAttribute('startWidth', parseInt(curTarget.offsetWidth));
curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
curTarget.style.display = 'none';

// loop through each possible drop container
for(var i=0; i<dragConts.length; i++){
with(dragConts[i]){
var pos = getPosition(dragConts[i]);

/**//*
save the width, height and position of each container.

Even though we are saving the width and height of each
container back to the container this is much faster because
we are saving the number and do not have to run through
any calculations again. Also, offsetHeight and offsetWidth
are both fairly slow. You would never normally notice any
performance hit from these two functions but our code is
going to be running hundreds of times each second so every
little bit helps!

Note that the biggest performance gain here, by far, comes
from not having to run through the getPosition function
hundreds of times.
*/
setAttribute('startWidth', parseInt(offsetWidth));
setAttribute('startHeight', parseInt(offsetHeight));
setAttribute('startLeft', pos.x);
setAttribute('startTop', pos.y);
}

// loop through each child element of each container
for(var j=0; j<dragConts[i].childNodes.length; j++){
with(dragConts[i].childNodes[j]){
if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;

var pos = getPosition(dragConts[i].childNodes[j]);

// save the width, height and position of each element
setAttribute('startWidth', parseInt(offsetWidth));
setAttribute('startHeight', parseInt(offsetHeight));
setAttribute('startLeft', pos.x);
setAttribute('startTop', pos.y);
}
}
}
}
}

// If we get in here we are dragging something
if(curTarget){
// move our helper div to wherever the mouse is (adjusted by mouseOffset)
dragHelper.style.top = mousePos.y - mouseOffset.y;
dragHelper.style.left = mousePos.x - mouseOffset.x;

var dragConts = DragDrops[curTarget.getAttribute('DragObj')];
var activeCont = null;

var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);
var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2);

// check each drop container to see if our target object is "inside" the container
for(var i=0; i<dragConts.length; i++){
with(dragConts[i]){
if(((getAttribute('startLeft')) < xPos) &&
((getAttribute('startTop')) < yPos) &&
((getAttribute('startLeft') + getAttribute('startWidth')) > xPos) &&
((getAttribute('startTop') + getAttribute('startHeight')) > yPos)){

/**//*
our target is inside of our container so save the container into
the activeCont variable and then exit the loop since we no longer
need to check the rest of the containers
*/
activeCont = dragConts[i];

// exit the for loop
break;
}
}
}

// Our target object is in one of our containers. Check to see where our div belongs
if(activeCont){
// beforeNode will hold the first node AFTER where our div belongs
var beforeNode = null;

// loop through each child node (skipping text nodes).
for(var i=activeCont.childNodes.length-1; i>=0; i--){
with(activeCont.childNodes[i]){
if(nodeName=='#text') continue;

// if the current item is "After" the item being dragged
if(
curTarget != activeCont.childNodes[i] &&
((getAttribute('startLeft') + getAttribute('startWidth')) > xPos) &&
((getAttribute('startTop') + getAttribute('startHeight')) > yPos)){
beforeNode = activeCont.childNodes[i];
}
}
}

// the item being dragged belongs before another item
if(beforeNode){
if(beforeNode!=curTarget.nextSibling){
activeCont.insertBefore(curTarget, beforeNode);
}

// the item being dragged belongs at the end of the current container
} else {
if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
activeCont.appendChild(curTarget);
}
}

// make our drag item visible
if(curTarget.style.display!=''){
curTarget.style.display = '';
}
} else {

// our drag item is not in a container, so hide it.
if(curTarget.style.display!='none'){
curTarget.style.display = 'none';
}
}
}

// track the current mouse state so we can compare against it next time
lMouseState = iMouseDown;

// mouseMove target
lastTarget = target;

// track the current mouse state so we can compare against it next time
lMouseState = iMouseDown;

// this helps prevent items on the page from being highlighted while dragging
return false;
}

function mouseUp(ev){
if(curTarget){
// hide our helper object - it is no longer needed
dragHelper.style.display = 'none';

// if the drag item is invisible put it back where it was before moving it
if(curTarget.style.display == 'none'){
if(rootSibling){
rootParent.insertBefore(curTarget, rootSibling);
} else {
rootParent.appendChild(curTarget);
}
}

// make sure the drag item is visible
curTarget.style.display = '';
}
curTarget = null;
iMouseDown = false;
}

function mouseDown(){
iMouseDown = true;
if(lastTarget){
return false;
}
}

document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup = mouseUp;

window.onload = function(){
// Create our helper object that will show the item while dragging
dragHelper = document.createElement('DIV');
dragHelper.style.cssText = 'position:absolute;display:none;';

CreateDragContainer(
document.getElementById('DragContainer1'),
document.getElementById('DragContainer2'),
document.getElementById('DragContainer3')
);

document.body.appendChild(dragHelper);
}



<!-- the mouse over and dragging class are defined on each item -->
<div class ="DragContainer" id="DragContainer1">
<div class="DragBox" id="Item1" overClass="OverDragBox" dragClass="DragDragBox">Item #1</div>
<div class="DragBox" id="Item2" overClass="OverDragBox" dragClass="DragDragBox">Item #2</div>
<div class="DragBox" id="Item3" overClass="OverDragBox" dragClass="DragDragBox">Item #3</div>
<div class="DragBox" id="Item4" overClass="OverDragBox" dragClass="DragDragBox">Item #4</div>
</div>
<div class="DragContainer" id="DragContainer2" >
<div class="DragBox" id="Item5" overClass="OverDragBox" dragClass="DragDragBox">Item #5</div>
<div class="DragBox" id="Item6" overClass="OverDragBox" dragClass="DragDragBox">Item #6</div>
<div class="DragBox" id="Item7" overClass="OverDragBox" dragClass="DragDragBox">Item #7</div>
<div class="DragBox" id="Item8" overClass="OverDragBox" dragClass="DragDragBox">Item #8</div>
</div>
<div class="DragContainer" id="DragContainer3">
<div class="DragBox" id="Item9" overClass="OverDragBox" dragClass="DragDragBox">Item #9</div>
<div class="DragBox" id="Item10" overClass="OverDragBox" dragClass="DragDragBox">Item #10</div>
<div class="DragBox" id="Item11" overClass="OverDragBox" dragClass="DragDragBox">Item #11</div>
<div class="DragBox" id="Item12" overClass="OverDragBox" dragClass="DragDragBox">Item #12</div>
</div>







Mark Kahn Web Developer、DBA。 :http://www.jslibrary.org

}
この例では、マウスが解放されると、マウスポインタがターゲット上にある場合、ターゲット要素の左側の横軸(mousePos.x>targPos.x)よりも大きいマウスの横軸を持つイベントがあります。Y座標についても同じ判断をします。これらの値がすべてtrueに戻ると、マウスはターゲット要素の範囲内にあります。
  • ドラゴdrop.rar(4.4 KB)
  • 説明:JSのソースコードの実現をドラッグして