前言:
萤火虫的光点虽然微弱,但亮着便是向黑暗挑战
--------------------------------正文---------------------------------
js代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 200px;
height: 200px;
background: red;
position: absolute;
left: 0;
top: 0;
}
#box2{
width: 200px;
height: 200px;
background: green;
position: absolute;
right: 0;
top: 0;
}
</style>
<script>
function drag(id){
var oBox = document.getElementById(id);
oBox.onmousedown = function(ev){
var oEvent = ev||event;
// 鼠标到页面的距离减去被拖拽对象当前到页面的距离
var disX = oEvent.clientX-oBox.offsetLeft; //鼠标到被拖拽对象边框的距离
var disY = oEvent.clientY-oBox.offsetTop;
document.onmousemove = function(ev){
var oEvent = ev||event;
//鼠标到页面的距离减去鼠标到被拖拽对象边框的距离
var l = oEvent.clientX-disX; //被拖拽对象到页面的距离
var t = oEvent.clientY-disY;
if(l<0){
l = 0;
}else if(l>document.documentElement.clientWidth-oBox.offsetWidth){
l = document.documentElement.clientWidth-oBox.offsetWidth;
}
if(t<0){
t = 0;
}else if(t>document.documentElement.clientHeight-oBox.offsetHeight){
t = document.documentElement.clientHeight-oBox.offsetHeight;
}
oBox.style.left = l+'px';
oBox.style.top = t+'px';
};
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
oBox.releaseCapture&&oBox.releaseCapture();
};
oBox.setCapture&&oBox.setCapture();
return false;
};
}
window.onload = function(){
drag('box');
drag('box2');
};
</script>
</head>
<body>
<div id="box"></div>
<div id="box2"></div>
</body>
</html>
jQuery代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
div{
width: 200px;
height: 200px;
background: red;
position: absolute;
left: 0;
top: 0;
}
</style>
<script src="jquery-1.9.1.min.js"></script>
</head>
<body>
<div id="box"></div>
<script>
$(document).ready(function(){
$('#box').on('mousedown',function(ev){
// 鼠标到页面的距离减去被拖拽对象当前到页面的距离
var disX = ev.clientX-$(this).position().left; //鼠标到被拖拽对象边框的距离
var disY = ev.clientY-$(this).position().top;
function fnMove(ev){
$('#box').css({
//鼠标到页面的距离减去鼠标到被拖拽对象边框的距离
left: ev.clientX-disX+'px', //被拖拽对象到页面的距离
top: ev.clientY-disY+'px'
});
}
function fnUp(){
$(document).off('mousemove',fnMove);
$(document).off('mouseup',fnUp);
}
$(document).on('mousemove',fnMove);
$(document).on('mouseup',fnUp);
return false;
});
});
</script>
</body>
</html>