zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

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

<!DOCTYPEHTML>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>测试的拖拽功能</title>
<styletype="text/css">
body,div{margin:0;paading:0;font-size:12px;}
body{width:960px;margin:0auto;}
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:25px000;padding:5px;border:1pxsolid#f00;}
.main{position:static;width:600px;height:80px;margin-bottom:5px;border:1pxsolidblue;background:#ccc;}
.maindash{position:absolute;width:600px;height:80px;margin-bottom:5px;border:1pxdashedblue;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:1pxdashed#f00;};
</style>
<scripttype="text/javascript"src="jquery-1.6.1.min.js"></script>
<scripttype="text/javascript">
$(document).ready(function(){
varrange={x:0,y:0};//鼠标元素偏移量
varlastPos={x:0,y:0,x1:0,y1:0};//拖拽对象的四个坐标
vartarPos={x:0,y:0,x1:0,y1:0};//目标元素对象的坐标初始化
vartheDiv=null,move=false;//拖拽对象拖拽状态
vartheDivId=0,theDivHeight=0,theDivHalf=0;tarFirstY=0;//拖拽对象的索引、高度、的初始化。
vartarDiv=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");
//创建新元素插入拖拽元素之前的位置(虚线框)
$("<divclass="dash"></div>").insertBefore(theDiv);
});
});
$(document).mousemove(function(event){
if(!move)returnfalse;
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.x=tarDiv.offset().left;
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>
<divclass="box"id="box">
<divclass="main"id="main0">div1</div>
<divclass="main"id="main1">div2</div>
<divclass="main"id="main2">div3</div>
<divclass="main"id="main3">div4</div>
<divclass="main"id="main4">div5</div>
</div>
</body>
</html>