DIV CSS 佈局教程網

原生 JavaScript 拖曳實作:一個可複用的 drag 函式
編輯:關於JavaScript     

不依賴任何框架,把拖曳邏輯封裝成一個函式,傳入被拖曳元素與拖曳把手即可使用。

 function drag(t,p){ var point = p || null, target = t || null, resultX = 0, resultY = 0; (!point)? point = target : ''; //如果沒有拖動點,則拖動點默認為整個被拖動元素 function getPos(t){ var offsetLeft = 0, offsetTop = 0, offsetParent = t; while(offsetParent){ offsetLeft+=offsetParent.offsetLeft; offsetTop+=offsetParent.offsetTop; offsetParent = offsetParent.offsetParent; } return {'top':offsetTop,'left':offsetLeft}; } function core(){ var width = document.body.clientWidth || document.documentElement.clientWidth, height = document.body.clientHeight || document.documentElement.clientHeight; maxWidth = width - target.offsetWidth; maxHeight = height - target.offsetHeight; (resultX >= maxWidth)? target.style.left = maxWidth+'px' : (resultX > 0)?target.style.left = resultX +'px': ''; //重置默認位置。 (resultY >= maxHeight)? target.style.top = maxHeight +'px' : (resultY > 0)?target.style.top = resultY +'px':''; //重置默認位置。 point.onmousedown=function(e){ var e = e || window.event, coordX = e.clientX, coordY = e.clientY, posX = getPos(target).left, posY = getPos(target).top; point.setCapture && point.setCapture(); //將Mouse事件鎖定到指定元素上。 document.onmousemove=function(e){ var ev = e || window.event, moveX = ev.clientX, moveY = ev.clientY; resultX = moveX - (coordX - posX); //結果值是坐標點減去被拖動元素距離瀏覽器左側的邊距 resultY = moveY - (coordY - posY); (resultX > 0 )?((resultX < maxWidth)?target.style.left = resultX+'px' : target.style.left = maxWidth+'px') : target.style.left = '0px'; (resultY > 0 )?((resultY < maxHeight)?target.style.top = resultY+'px' : target.style.top = maxHeight+'px') : target.style.top = '0px'; ev.stopPropagation && ev.stopPropagation(); ev.preventDefault; ev.returnValue = false; ev.cancelBubble = true; }; }; document.onmouseup=function(){ // 解決拖動時,當鼠標指向的DOM對象非拖動點元素時,無法觸發拖動點的onmousedown的BUG。 document.onmousemove = null; point.releaseCapture && point.releaseCapture(); // 將Mouse事件從指定元素上移除。 }; point.onmouseup=function(e){ var e = e || window.event; document.onmousemove = null; point.releaseCapture && point.releaseCapture(); }; } core(); window.onresize = core; } 

使用方式

 drag(t,p) /* * 說明 * t 表示被拖動的元素 * p 表示拖動點 */ // 注意:如果省略拖動點,默認可拖動的區域是整個被拖動元素 

幾個設計上的關鍵點:

getPos 沿著 offsetParent 鏈往上累加,取得元素相對於頁面的真實座標,避免多層巢狀時位置算錯。core 在初始化與視窗 resize 時各跑一次,即時更新可拖曳的邊界,元素不會被拖出視窗外。setCapture / releaseCapture 則用來鎖定滑鼠事件,防止拖太快時游標跑出元素導致 onmousedown 失效——這是 IE 時代的經典解法,現代瀏覽器雖已支援 Pointer Events,但這個思路仍然值得理解。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved