我正在使用以下函数通过句柄拖动 div:
function enableDragging(ele) {
var dragging = dragging || false,
x, y, Ox, Oy,
current;
enableDragging.z = enableDragging.z || 1;
var grabber = document.getElementById("myHandelDiv");
grabber.onmousedown = function(ev) {
current = ev.target.parentNode;
dragging = true;
x = ev.clientX;
y = ev.clientY;
Ox = current.offsetLeft;
Oy = current.offsetTop;
current.style.zIndex = ++enableDragging.z;
console.log(dragging);
window.onmousemove = function(ev) {
pauseEvent(ev);
if (dragging == true) {
var Sx = ev.clientX - x + Ox,
Sy = ev.clientY - y + Oy;
current.style.top = Sy + "px";
current.style.left = Sx + "px";
document.body.focus();
// prevent text selection in IE
document.onselectstart = function () { return false; };
// prevent IE from trying to drag an image
ev.ondragstart = function() { return false; };
return false;
}
};
window.onmouseup = function(ev) {
dragging && (dragging = false);
}
};
}
function pauseEvent(e){
if(e.stopPropagation) e.stopPropagation();
if(e.preventDefault) e.preventDefault();
e.cancelBubble=true;
e.returnValue=false;
return false;
}
我有两个问题:
- 在 IE 7 和 8 中不起作用,由于某种原因,我没有收到任何错误。
- 拖动时在某些浏览器上选择了文本,导致拖动出现滞后
我像这样启动拖动:
var ele = document.getElementById("divDragWrapper");
enableDragging(ele);
更新,我现在在 IE 中收到此错误:
SCRIPT5007:无法获取属性“目标”的值:对象为空或未定义
在这一行: current = ev.target.parentNode;