|
當(dāng)鼠標(biāo)點(diǎn)擊div時(shí),觸發(fā)一個(gè)事件,讓div的位置屬性(left,top)隨著鼠標(biāo)位置變化而變化,當(dāng)鼠標(biāo)釋放后,div的位置屬性就用了鼠標(biāo)釋放時(shí)的位置。
鼠標(biāo)點(diǎn)擊時(shí)觸發(fā)事件是很容易做到的,只要在div的標(biāo)簽里加上onmouseclick就可以了,現(xiàn)在我們要解決的問題是如何讓div的位置隨著鼠標(biāo)的位置變化而變化。
雖然這可能是一個(gè)很簡(jiǎn)單的推理過程,不過還是羅嗦點(diǎn)說清楚吧。div的left和top是div左上角的坐標(biāo),當(dāng)我們把鼠標(biāo)移到div中點(diǎn)擊的時(shí)候,無疑鼠標(biāo)的坐標(biāo)和div的坐標(biāo)是不一致的,這時(shí)候如果我們簡(jiǎn)單的讓div的坐標(biāo)等于鼠標(biāo)的坐標(biāo),那么看起來的效果就不是那么完美了,所以我們先要得到鼠標(biāo)的坐標(biāo)和div坐標(biāo)的差,然后在鼠標(biāo)移動(dòng)到的時(shí)候,在鼠標(biāo)坐標(biāo)上減去這個(gè)差來得到div的坐標(biāo)(如果不太明白,那就先補(bǔ)習(xí)一下網(wǎng)頁的基礎(chǔ)知識(shí))。
接下來的事情就簡(jiǎn)單了,當(dāng)鼠標(biāo)移動(dòng)的時(shí)候,我們不斷的計(jì)算得到div的坐標(biāo),并改變,在鼠標(biāo)釋放的時(shí)候,這個(gè)事件就被移除。
整個(gè)js函數(shù)如下:
function beginDrag(elementToDrag,event)
{
var deltaX=event.clientX-parseInt(elementToDrag.style.left);
var deltaY=event.clientY-parseInt(elementToDrag.style.top);
if(document.addEventListener)
{
document.addEventListener(”mousemove”,moveHandler,true);
document.addEventListener(”mouseup”,upHandler,true);
//document.addEventListener(”mouseout”,upHandler,true);
}
else if(document.attachEvent)
{
document.attachEvent(”onmousemove”,moveHandler);
document.attachEvent(”onmouseup”,upHandler);
//document.attachEvent(”onmouseout”,upHandler);
}
if(event.stopPropagation) event.stopPropagation();
else event.cancelBubble=true;
if(event.preventDefault) event.preventDefault();
else event.returnValue=false;
function moveHandler(e)
{
if (!e) e=window.event; //如果是IE的事件對(duì)象,那么就用window.event
//全局屬性,否則就用DOM二級(jí)標(biāo)準(zhǔn)的Event對(duì)象。
elementToDrag.style.left=(e.clientX-deltaX)+”px”;
elementToDrag.style.top=(e.clientY-deltaY)+”px”;
if(e.stopPropagation) e.stopPropagation();
else e.cancelBubble=true;
}
function upHandler(e)
{
if(document.removeEventListener)
{
document.removeEventListener(”mouseup”,upHandler,true);
document.removeEventListener(”mousemove”,moveHandler,true);}
else
{
document.detachEvent(”onmouseup”,upHandler);
document.detachEvent(”onmousemove”,moveHandler);}
}
if (!e) e=window.event;
if(e.stopPropagation) e.stopPropagation();
else e.cancelBubble=true;
}
JavaScript技術(shù):可以拖動(dòng)的div 實(shí)現(xiàn)代碼第1/2頁,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。