做这个不难,主要是理解了计算的公式吧,鼠标移动的位置-(鼠标按下的位置-要移动div与浏览器的边距)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>有问题的代码</title>
<style>
* {
margin: 0;
padding: 0;
}
.header p {
position: absolute;
right: 20px;
top: 10px;
}
#header-login-box {
display: none;
width: 200px;
height: 200px;
border: 1px solid #000;
margin-left: 200px;
margin-top: 200px;
}
.login-title {
padding: 10px 0;
border-bottom: 1px solid #dddddd;
cursor: move;
}
</style>
</head>
<body>
<div class="header">
<p id="login">登陆</p>
</div>
<div id="header-login-box">
<div class="login-title">可以拖动的div</div>
</div>
</body>
<script src="jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
var divX = 0;
var divY = 0;
var mouseX = 0;
var mouseY = 0;
var difX;
var difY;
var isDown = false;
$("#login").on("click", function () {
$("#header-login-box").show();
$(".login-title").mousedown(function (e) {
isDown = true;
divX = $("#header-login-box").offset().left;
divY = $("#header-login-box").offset().top;
difX = e.pageX - divX;
difY = e.pageY - divY;
})
$(document).mousemove(function (e) {
if (isDown == true) {
newX = e.pageX - difX;
newY = e.pageY - difY;
$("#header-login-box").css("margin-left", newX + "px").css("margin-top", newY + "px");
}
}).mouseup(function (e) {
isDown = false;
})
})
});
</script>
</html>