js拖拽bug修復

前幾天有朋友對於js拖拽組件提出有一個bug,就是改變窗口大小,外層div限制就會錯亂,我看了下確實是這樣,原因是我用的窗口的絕對定位,窗口改變沒有重新計算的話就會導致問題,分析了下,外側給limit的div可以用relative佈局,然後拖動的div就按照相對位置計算即可,下面重新記錄下改正後的代碼


<code>; (function (root) {

//定義組件函數
var Dragable = function () { };

//判讀對象是否為dom對象
function isElement(element) {
return element instanceof Element || element instanceof HTMLDocument;
}
/**
*
* @param {新的位置} pos
* @param {拖動div信息} dragRect
* @param {外層div信息} limitRect
*/
function calcPosition(pos, dragRect, limitRect) {
if (pos.x < 0) {
pos.x = 0;
}
if (pos.y < 0) {
pos.y = 0;
}
if (pos.x + dragRect.width >= limitRect.width) {
pos.x = limitRect.width - dragRect.width;
}
if (pos.y + dragRect.height >= limitRect.height) {
pos.y = limitRect.height - dragRect.height
}
return pos;
}

Dragable.prototype.regist = function (el, limit) {
//傳入的對象必須為dom對象,limit也是
if (!isElement(el)) {
console.error("the el must be dom elment");
return;
}
var limitRect = null;
if (limit && isElement(limit)) {
limitRect = {width: limit.clientWidth, height: limit.clientHeight }
}

//convert the elent to absolute
el.style.position = 'absolute';
el.addEventListener('mousedown', function (e) {

var dragRect = { left: el.offsetLeft, top: el.offsetTop, width: el.offsetWidth, height: el.offsetHeight }
//獲取x座標和y座標
var downX = e.clientX;
var downY = e.clientY;


//開關打開
var isDown = true;
//設置樣式
el.style.cursor = 'move';

window.onmousemove = function (e) {
if (!isDown) {
return;
}
var newLeft = e.clientX - downX + dragRect.left;
var newTop = e.clientY - downY + dragRect.top;

var newPos = calcPosition({ x: newLeft, y: newTop }, dragRect, limitRect);

el.style.left = newPos.x + 'px';
el.style.top = newPos.y + 'px';

return false;
}

window.onmouseup = function (e) {
//開關關閉
isDown = false;
el.style.cursor = 'default';
return false;
}
e.preventDefault();
});

}


//將組件掛在到window對象
root.Dragable = Dragable;
})(window);/<code>


分享到:


相關文章: