原生js實現節點拖拽
阿新 • • 發佈:2019-02-12
var Drags = function (element, callback) {
callback = callback || function () {};
var params = {
top: 0,
left: 0,
currentX: 0,
currentY: 0,
flag: false
};
function getCss(element, key) {
return element.currentStyle ? element.currentStyle[key] : document.defaultView.getComputedStyle(element,null)[key];
// ie用currentStyle
}
var lefts = getCss(element, "left"),
tops = getCss(element, "top" );
params.left = lefts !== "auto" ? lefts : 0;
params.top = tops !== "auto" ? tops : 0;
element.onmousedown = function (event) {
params.flag = true;
event = event || window.event; // ie用後面
params.currentX = event.clientX;
params.currentY = event.clientY;
};
document.onmousemove = function (event) {
event = event || window.event;
if (params.flag) {
// 現在位置
var nowX = event.clientX,
nowY = event.clientY,
// 需要移動的距離
disX = nowX - params.currentX,
disY = nowY - params.currentY;
element.style.left = parseInt(params.left) + disX + "px";
element.style.top = parseInt(params.top) + disY + "px";
}
};
document.onmouseup = function () {
params.flag = false;
var lefts = getCss(element, "left"),
tops = getCss(element, "top");
params.left = lefts !== "auto" ? lefts : 0;
params.top = tops !== "auto" ? tops : 0;
}
}(document.getElementById('drag'));