Home  >  Article  >  Web Front-end  >  简单的jquery拖拽排序效果实现代码_jquery

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

WBOY
WBOYOriginal
2016-05-16 18:02:011220browse

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

复制代码 代码如下:





测试的拖拽功能


").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.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 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;
});
});




div1

div2

div3

div4

div5




Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn