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>


分享到:


相關文章: