<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<style type="text/css">
.drag {
position: absolute;
background: #0000CC;
top: 100px;
left: 200px;
padding: 0;
width: 100px;
height: 100px;
}
</style>
<body>
<div class="drag">
</div>
<script src="style/js/jquery-1.12.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function() {
var move = false; //移动标记
var _x, _y; //鼠标离控件左上角的相对位置
$(".drag").mousedown(function(e) {
$(this).css({
"cursor": "move"
})
move = true;
_x = e.pageX - parseInt($(".drag").css("left"));
_y = e.pageY - parseInt($(".drag").css("top"));
});
$(document).mousemove(function(e) {
if(move) {
var x = e.pageX - _x; //控件左上角到屏幕左上角的相对位置
var y = e.pageY - _y;
$(".drag").css({
"top": x+'px',
"left": y+'px'
});
}
}).mouseup(function() {
move = false;
});
});
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<style type="text/css">
.drag {
position: absolute;
background: #0000CC;
top: 100px;
left: 200px;
padding: 0;
width: 100px;
height: 100px;
}
</style>
<body>
<div class="drag">
</div>
<script src="style/js/jquery-1.12.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function() {
var move = false; //移动标记
var _x, _y; //鼠标离控件左上角的相对位置
$(".drag").mousedown(function(e) {
$(this).css({
"cursor": "move"
})
move = true;
_x = e.pageX - parseInt($(".drag").css("left"));
_y = e.pageY - parseInt($(".drag").css("top"));
});
$(document).mousemove(function(e) {
if(move) {
var x = e.pageX - _x; //控件左上角到屏幕左上角的相对位置
var y = e.pageY - _y;
$(".drag").css({
"top": x+'px',
"left": y+'px'
});
}
}).mouseup(function() {
move = false;
});
});
</script>
</body>
</html>