原生JS拖拽和jQuery拖拽的实现
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
* { margin:0; padding:0;}
#div1 { width:100px; height:100px; background:red; position:absolute;}
</style>
<script type="text/javascript" src="jquery-1.12.3.min.js"></script>
<script>
/* 原生js写拖拽
window.onload = function(){
var oDiv = document.getElementById('div1');
oDiv.onmousedown = function(ev){
var ev = ev || event;
disL = ev.clientX - oDiv.offsetLeft;
disT = ev.clientY - oDiv.offsetTop;
maxL = document.documentElement.clientWidth - oDiv.offsetWidth;
maxT = document.documentElement.clientHeight - oDiv.offsetHeight;
document.onmousemove = function(ev){
var ev = ev || event;
disX = ev.clientX - disL;
disY = ev.clientY - disT;
if(disX <= 0){disX = 0;}
if(disY <= 0){disY = 0;}
if(disX >= maxL){disX = maxL;}
if(disY >= maxT){disY = maxT;}
oDiv.style.left = disX + 'px';
oDiv.style.top = disY + 'px';
}
}
document.onmouseup = function(ev){
var ev = ev || event;
document.onmousemove = null;
}
};
*/
$(function(){
var disX = 0;
var disY = 0;
$('#div1').mousedown(function(ev){
disX = ev.pageX - $(this).offset().left;
disY = ev.pageY - $(this).offset().top;
$(document).mousemove(function(ev){
$('#div1').css('left',ev.pageX - disX);
$('#div1').css('top',ev.pageY - disY);
});
});
$('#div1').mouseup(function(){
$(document).off();
});
return false; //阻止冒泡事件
});
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>