實作步驟:
具體代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>測試的拖拽功能</title>
<style type="text/css">
body, div { margin: 0; padding: 0; font-size: 12px; }
body { width: 960px; margin: 0 auto; }
ul, li { margin: 0; padding: 0; list-style: none; }
.box { width: 600px; margin: 25px 0 0 0; padding: 5px; border: 1px solid #f00; }
.main { position: static; width: 600px; height: 80px; margin-bottom: 5px; border: 1px solid blue; background: #ccc; }
.maindash { position: absolute; width: 600px; height: 80px; margin-bottom: 5px; border: 1px dashed blue; background: #ececec; opacity: 0.7; }
.dash { position: static; width: 600px; height: 80px; margin-bottom: 5px; border: 1px dashed #f00; }
</style>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready( function () {
var range = { x: 0, y: 0 };//滑鼠元素偏移量
var lastPos = { x: 0, y: 0, x1: 0, y1: 0 }; //拖拽物件的四個坐標
var tarPos = { x: 0, y: 0, x1: 0, y1: 0 }; //目標元素坐標
var theDiv = null, move = false;//拖拽物件與拖拽狀態
var theDivId =0, theDivHeight = 0, theDivHalf = 0; tarFirstY = 0;
var tarDiv = null, tarFirst, tempDiv; //目標元素、臨時虛線物件
$(".main").each(function(){
$(this).mousedown(function (event){
theDiv = $(this); //拖拽物件
range.x = event.pageX - theDiv.offset().left;
range.y = event.pageY - theDiv.offset().top;
theDivId = theDiv.index();
theDivHeight = theDiv.height();
theDivHalf = theDivHeight/2;
move = true;
theDiv.attr("class","maindash");
//建立虛線框,插入拖拽元素之前的位置
$("<div class='dash'></div>").insertBefore(theDiv);
});
});
$(document).mousemove(function(event) {
if (!move) return false;
lastPos.x = event.pageX - range.x;
lastPos.y = event.pageY - range.y;
lastPos.y1 = lastPos.y + theDivHeight;
//拖拽元素隨滑鼠移動
theDiv.css({left: lastPos.x + 'px',top: lastPos.y + 'px'});
var $main = $('.main');
tempDiv = $(".dash"); //臨時虛線框物件
$main.each(function () {
tarDiv = $(this);
tarPos.y = tarDiv.offset().top;
tarPos.y1 = tarPos.y + tarDiv.height()/2;
tarFirst = $main.eq(0); //第一個元素
tarFirstY = tarFirst.offset().top + theDivHalf; //第一個元素中心縱坐標
if (lastPos.y <= tarFirstY) { //移動到第一個位置
tempDiv.insertBefore(tarFirst);
}
if (lastPos.y >= tarPos.y - theDivHalf && lastPos.y1 >= tarPos.y1 ) {
tempDiv.insertAfter(tarDiv);
}
});
}).mouseup(function(event) {
theDiv.insertBefore(tempDiv); //插入到虛線div的位置
theDiv.attr("class", "main"); //恢復初始樣式
tempDiv.remove(); //刪除虛線div
move=false;
});
});
</script>
</head>
<body>
<div class="box" id="box">
<div class="main" id="main0">div1</div>
<div class="main" id="main1">div2</div>
<div class="main" id="main2">div3</div>
<div class="main" id="main3">div4</div>
<div class="main" id="main4">div5</div>
</div>
</body>
</html>
整體原理是:在 mousedown 時記錄拖拽元素與滑鼠偏移、建立一個虛線佔位框;在 mousemove 時讓元素隨滑鼠移動,並比對各元素中心坐標,動態調整虛線框的插入位置;最後在 mouseup 時將元素插入到虛線框所在位置,還原樣式並移除虛線框,即可完成拖拽排序。