jQuery实现div横向拖拽排序的简单实例

2020-05-29 06:59:47易采站长站整理

实例如下:


<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>div横向拖拽排序</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<style type="text/css">
body,div{
padding: 0px;
margin: 0px;
}

.box {
margin-left: 15px;
padding : 10px;
padding-right: 0px;
width : 810px;
height : 150px;
border : blue solid 1px;
}

.horizontal-div{
float : left;
margin-right: 10px;
border: #000 solid 1px;
text-align: center;
width : 150px;
height : 150px;
}

.horizontal-div-dash {
position: absolute;
width: 150px;
height: 150px;
margin-right: 10px;
border: 1px dashed blue;
background: #ececec;
opacity: 0.7;
}

.dash {
float : left;
width: 150px;
height: 150px;
margin-right: 10px;
border: 1px dashed #f00;
};
</style>

<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; choose = false; //拖拽对象 拖拽状态 选中状态
var theDivId =0, theDivHeight = 0, theDivHalf = 0; tarFirstY = 0; //拖拽对象的索引、高度、的初始化。
var tarDiv = null, tarFirst, tempDiv; //要插入的目标元素的对象, 临时的虚线对象
var initPos = {x: 0, y: 0};
$(".horizontal-div").each(function(){
$(this).mousedown(function (event){
choose = true;
//拖拽对象
theDiv = $(this);
//记录拖拽元素初始位置
initPos.x = theDiv.offset().left;
initPos.y = theDiv.offset().top;
//鼠标元素相对偏移量
range.x = event.pageX - theDiv.offset().left;
range.y = event.pageY - theDiv.offset().top;
theDivId = theDiv.index();
theDivWidth = theDiv.width();
theDivHalf = theDivWidth/2;
theDiv.attr("class","horizontal-div-dash");
theDiv.css({left: initPos.x + 'px',top: initPos.y + 'px'});
// 创建新元素 插入拖拽元素之前的位置(虚线框)
$("<div class='dash'></div>").insertBefore(theDiv);
tempDiv = $(".dash");
});
});

$(document).mouseup(function(event) {
if(!choose){return false;}
if(!move){
theDiv.attr("class", "horizontal-div");
tempDiv.remove(); // 删除新建的虚线div
choose = false;
return false;
}
theDiv.insertBefore(tempDiv); // 拖拽元素插入到 虚线div的位置上
theDiv.attr("class", "horizontal-div"); //恢复对象的初始样式
tempDiv.remove(); // 删除新建的虚线div
move = false;
choose = false;