前言:
螢火蟲(chóng)的光點(diǎn)雖然微弱,但亮著便是向黑暗挑戰(zhàn)
--------------------------------正文---------------------------------
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;
// 鼠標(biāo)到頁(yè)面的距離減去被拖拽對(duì)象當(dāng)前到頁(yè)面的距離
var disX = oEvent.clientX-oBox.offsetLeft; //鼠標(biāo)到被拖拽對(duì)象邊框的距離
var disY = oEvent.clientY-oBox.offsetTop;
document.onmousemove = function(ev){
var oEvent = ev||event;
//鼠標(biāo)到頁(yè)面的距離減去鼠標(biāo)到被拖拽對(duì)象邊框的距離
var l = oEvent.clientX-disX; //被拖拽對(duì)象到頁(yè)面的距離
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){
// 鼠標(biāo)到頁(yè)面的距離減去被拖拽對(duì)象當(dāng)前到頁(yè)面的距離
var disX = ev.clientX-$(this).position().left; //鼠標(biāo)到被拖拽對(duì)象邊框的距離
var disY = ev.clientY-$(this).position().top;
function fnMove(ev){
$('#box').css({
//鼠標(biāo)到頁(yè)面的距離減去鼠標(biāo)到被拖拽對(duì)象邊框的距離
left: ev.clientX-disX+'px', //被拖拽對(duì)象到頁(yè)面的距離
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>