JQuery 拖拽元素,并移动其他元素位置
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>拖动元素,并移动其他元素</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<style>
span{
border: 1px solid;
margin-left: 10px;
}
</style>
</head>
<body class="layui-anim layui-anim-up" style="overflow-x: auto;">
<div id="app">
<span index="1" ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)"">
元素1
</span>
<span index="2" ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)">
元素2
</span>
<span index="3" ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)">
元素3
</span>
<span index="4" ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)"">
元素4
</span>
<span index="5" ondrop="drop(event,this)" ondragover="allowDrop(event)" draggable="true" ondragstart="drag(event, this)">
元素5
</span>
</div>
<script type="text/javascript" src="../js/jquery.js"></script>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
var source = null;
var index, text;
function drag(ev, current) {
source = current;
index = $(current).attr('index');
text = $(current).text();
}
function drop(ev, current) {
ev.preventDefault();
if(index < $(current).attr('index')){
moveDown(source, current);
}else{
moveTop(source, current);
}
$(current).text(text);
}
function moveDown(se, ce){
var t = $(se).next().text();
$(se).text(t);
se = $(se).next();
if($(se).attr('index') === $(ce).attr('index')){
return false;
}else if(se.length === 0){
return false;
}else{
moveDown(se, ce);
}
}
function moveTop(se, ce){
var t = $(se).prev().text();
$(se).text(t);
se = $(se).prev();
if($(se).attr('index') === $(ce).attr('index')){
return false;
}else if(se.length === 0){
return false;
}else{
moveTop(se, ce);
}
}
</script>
</body>
</html>