简单的jquery拖拽排序效果实现代码

2020-05-23 06:09:25易采站长站整理

步骤:
1.实现随鼠标移动的效果;
2.初始化一个元素及其坐标;
3.拖拽对象的最后坐标,与元素的坐标 进行计算和判断 来确定 要插入的目标元素;
4.用insertBefore 方法 插入到目标元素的前面
具体代码如下:

<!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; paading: 0; font-size: 12px; }
body { width: 960px; margin: 0 auto; }
ul, li { margin: 0; padding: 0; list-style: none; }
.clear { clear: both; width: 1px; height: 0px; line-height: 0px; font-size: 1px; }
.box { width: 600px; height: auto; 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; }
.hide { width: 600px; height: 80px; margin-bottom: 5px; }
.dash { position: sta;tic; 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’});
// 拖拽元素随鼠标移动 查找插入目标元素