您的位置:首页 > Web前端 > JQuery

jquery实现div拖拽

2018-05-10 09:18 218 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div拖拽</title>
<script src="../jquery-1.8.3.min.js"></script>
<style>
div{
position: absolute;
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
background: radial-gradient(yellow,red);
color:blue;
border-radius: 50%;
cursor: pointer;
}
</style>
</head>
<body>
<div>
按住鼠标移动div
</div>
<script>
$(function(){
//移动窗口的步骤
//1、按下鼠标左键
//2、移动鼠标
$('div').mousedown(function(e){
// e.pageX
var positionDiv = $(this).offset();
var distenceX = e.pageX - positionDiv.left;
var distenceY = e.pageY - positionDiv.top;
//alert(distenceX)
// alert(positionDiv.left);
$(document).mousemove(function(e){
var x = e.pageX - distenceX;
var y = e.pageY - distenceY;
if(x<0){
x=0;
}else if(x>$(document).width()-$('div').outerWidth(true)){
x = $(document).width()-$('div').outerWidth(true);
}
if(y<0){
y=0;
}else if(y>$(document).height()-$('div').outerHeight(true)){
y = $(document).height()-$('div').outerHeight(true);
}
$('div').css({
'left':x+'px',
'top':y+'px'
});
});
$(document).mouseup(function(){
$(document).off('mousemove');
});
});
});
</script>
</body>
</html>
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: