<div id="myBtn">
<div class="item"><img src="http://placehold.it/90x90/" alt=""></div>
<div class="item"><img src="http://placehold.it/91x91/" alt=""></div>
<div class="item"><img src="http://placehold.it/92x92/" alt=""></div>
<div class="item"><img src="http://placehold.it/93x93/" alt=""></div>
<div class="item"><img src="http://placehold.it/94x94/" alt=""></div>
<div class="item"><img src="http://placehold.it/95x95/" alt=""></div>
<div class="item"><img src="http://placehold.it/96x96/" alt=""></div>
<div class="item"><img src="http://placehold.it/97x97/" alt=""></div>
</div>
首先需要对浏览器做一些兼容性处理。代码如下:
function addHandler (element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
function getEvent (event) {
return event ? event : window.event;
}
function getTarget (event) {
return event.target || event.srcElement;
}
function preventDefault (event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
接下来使用drag的一系列事件来实现此功能。
代码如下:
var btn = document.getElementById('myBtn');
addHandler(btn, 'dragstart', function (e) {
btn.dragStartEle = getTarget(e);
})
addHandler(btn, 'dragover', function (e) {
preventDefault(e);
}, false);
addHandler(btn, 'dragenter', function (e) {
preventDefault(e);
}, false);
addHandler(btn, 'drop', function (e) {
var eleParent;
var target = getTarget(e);
preventDefault(e);
// 拖动元素,放置目标
if (btn.dragStartEle && target) {
if (target.nodeName === 'IMG' && btn.dragStartEle.nodeName === 'IMG') {
// 交换
eleParent = btn.dragStartEle.parentNode;
target.parentNode.appendChild(btn.dragStartEle);
eleParent.appendChild(target);
delete btn.dragStartEle;
}
}
}, false);
这样图片的拖拽排序功能就实现了。
jquery实现方式:
var $btn = $('#myBtn');
var dragStartEle;
$btn.on('dragstart', function (e) {
dragStartEle = e.target;
})
$btn.on('dragover', function (e) {
e.preventDefault();
});
$btn.on('dragenter', function (e) {
e.preventDefault();
});
$btn.on('drop', function (e) {
var $eleParent;
var target = e.target;
e.preventDefault();
// 拖动元素,放置目标
if (dragStartEle && target) {
if (target.nodeName === 'IMG' && dragStartEle.nodeName === 'IMG') {
// 交换
$eleParent = $(target).parent();
$(target).insertAfter(dragStartEle);
$eleParent.append(dragStartEle);
dragStartEle = undefined;
}
}
});