Главная > Javascript > Javascript: Drag & Drop (перетаскивание элементов)

Javascript: Drag & Drop (перетаскивание элементов)

Собственно Javascript:

var moveState = false;
var x0, y0;
var divX0, divY0;
function defPosition(event) {
	var x = y = 0;
	if (document.attachEvent != null) {
		x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
		y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
	if (!document.attachEvent && document.addEventListener) {
		x = event.clientX + window.scrollX;
		y = event.clientY + window.scrollY;
	}
	return {x:x, y:y};
}
function initMove(div, event) {
	var event = event || window.event;
	x0 = defPosition(event).x;
	y0 = defPosition(event).y;
	//divX0 = parseInt(div.style.left);
	//divY0 = parseInt(div.style.top);
	divX0 = absPosition(div).x;
	divY0 = absPosition(div).y;
	moveState = true;
}
document.onmouseup = function() {
	moveState = false;
}
function moveHandler(div, event) {
	var event = event || window.event;
	if (moveState) {
		div.style.left = divX0 + defPosition(event).x - x0;
		div.style.top = divY0 + defPosition(event).y - y0;
	}
}
function makeFastDrag(div, event) {
	document.onmousemove = function(event) {
		moveHandler(div, event);
	}
}
function absPosition(obj) {
	var x = y = 0;
	while(obj) {
		x += obj.offsetLeft;
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return {x:x, y:y};
}

HTML:

<div class='primer' onmousedown='initMove(this,event);' onmouseup = 'moveState = false;' onmousemove = 'makeFastDrag(this, event);'>Some Text</div>

CSS:

.primer {
	width: 150px;
	height: 100px;
	position: absolute;
	background: #000;
	cursor: move;
}

Использовались статьи:
http://fastcoder.org/articles/?aid=149
http://fastcoder.org/articles/?aid=16

Categories: Javascript Tags: ,
  1. Аноним
    Август 28th,2014 в 18:28 | #1

    не работает!

  2. Dem
    Сентябрь 5th,2011 в 16:12 | #2

    Спасибо, работает!

Похожие публикации