DIV拖拽

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 100px;
height: 100px;
background-color: #FFF0F5;
cursor:pointer;
            position:absolute;
            left:100px;
            top:100px;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script src="js/jquery-1.12.4.js"></script>
<script>
$(".box").on("mousedown",function (e){
console.log(e.pageX + "px" + e.pageY+"px");
var posi=$(this).offset();
var disX = e.pageX-posi.left;
var disY = e.pageY-posi.top;
console.log(disX,disY)
$(document).on('mousemove',function(e){
var x = e.pageX-disX;
var y = e.pageY-disY;
console.log(x,y);
if(x<0){
x=0;
}else if(x>$(document).width()-$(".box").outerWidth(true)){
x=$(document).width()-$(".box").outerWidth(true);
};
if(y<0){
y=0;
}else if(y>$(document).height()-$(".box").outerHeight(true)){
y=$(document).height()-$(".box").outerHeight(true);
}
$('.box').css({
'left':x+'px',
'top':y+'px'
});
});
$(document).mouseup(function(){
$(document).off('mousemove');
});
})


</script>
</html>
posted @ 2019-05-04 09:49  de玻璃  阅读(125)  评论(0编辑  收藏  举报