注意:
1:拖拽元素的位置(绝对定位)依赖于父级相对定位,如果把拖拽元素改为相对定位后,被拖拽元素的位置没有相对参照,会出现混乱的问题。
2:触发拖拽事件是鼠标滑过后即绑定。这样使得拖拽能即拖即用,体验上比较无缝一些

源码
html部分:

<!DOCTYPE html>

<html>

<head>

 <title></title>

 <style type="text/css">

 .box {

 width: 20px;

 height: 20px;

 top: 50px;

 left: 50px;

 position: absolute;

 background-color: red;

 }

 .wrap {

 position: relative;

 top: 10px;

 left: 10px;

 width: 500px;

 height: 500px;

 background: #f5f5f5;

 overflow: auto;

 }

 </style>

</head>

<body>

 <div class="wrap">

 </div>

 <script src="./resource/jquery-1.11.0.js"></script>

 <script src="./js/script.js"></script>

</body>

</html>

js部分

$(function() {

 for (var i = 0; i < 10; i++) {

 var dom = '<div class="box box' + i + '" color: #d4d4d4;"> + (50 / 1 + i / 1 * 40) + 'px"></div>'

 drag($('.box' + i))

 $('.wrap').append(dom)

 }

 // 鼠标滑过则添加拖拽事件

 $(".box").mouseenter(function() {

 drag(this)

 })

})

function drag(tag) {

 tag.onmousedown = function(e) {

 var e = e || window.event;

 var disX = tag.offsetLeft;

 var disY = tag.offsetTop;

 var x = e.pageX - disX;

 var y = e.pageY - disY;

 document.onmousemove = function(e) {

 var e = e || window.event;

 var left = e.pageX - x;

 var top = e.pageY - y;

 tag.style.left = left + "px";

 tag.style.top = top + "px";

 }

 }

 document.onmouseup = function(e) {

 document.onmousedown = null;

 document.onmousemove = null;

 console.log('=====')

 console.log(e.x, e.y)

 };

}

charlotteeeeeee
74 声望7 粉丝