1.用jQuery实现
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用JS实现拖拽</title>
<script src="jquery-1.11.1.min.js"></script>
<script>
(function($){
var dragging = false;
var object;
var mouseX;
var mouseY;
var objX;
var objY;
$.fn.myDrag=function(){
object=document.getElementById($(this).attr("id"));
object.onmousedown=mousedown;
object.onmousemove=mousemove;
object.onmouseup=mouseup;
object.style.position="relative";
object.style.top="0px";
object.style.left="0px";
}
function mousedown(event){
var event=event||window.event;
dragging=true;
mouseX=parseInt(event.clientX);
mouseY=parseInt(event.clientY);
objX=parseInt(object.style.left);
objY=parseInt(object.style.top);
}
function mousemove(event){
var event=event||window.event;
if(dragging==true){
var x,y;
y=event.clientY- mouseY + objY;
x=event.clientX- mouseX + objX;
object.style.left=x+"px";
object.style.top=y+"px";
}
}
function mouseup(event){
dragging=false;
}
})(jQuery);
$(document).ready(function(){
$("#test").myDrag();
})
</script>
</head>
<body>
<div id="test" style="border:1px solid; width:400px; background:#CCCCCC;">
<p>我是拖拽示例DIV。</p>
<p>可以试验一下效果。</p>
</div>
</body>
</html>
2.用JS实现
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用JS实现拖拽</title>
<script>
var dragging = false;
var object;
var mouseX;
var mouseY;
var objX;
var objY;
function myDrag(ID){
object=document.getElementById(ID);
object.onmousedown=mousedown;
object.onmousemove=mousemove;
object.onmouseup=mouseup;
object.style.position="relative";
object.style.top="0px";
object.style.left="0px";
}
function mousedown(event){
var event=event||window.event;
dragging=true;
mouseX=parseInt(event.clientX);
mouseY=parseInt(event.clientY);
objX=parseInt(object.style.left);
objY=parseInt(object.style.top);
}
function mousemove(event){
var event=event||window.event;
if(dragging==true){
var x,y;
y=event.clientY- mouseY + objY;
x=event.clientX- mouseX + objX;
object.style.left=x+"px";
object.style.top=y+"px";
}
}
function mouseup(event){
dragging=false;
}
window.onload=function(){
myDrag('test');
}
</script>
</head>
<body>
<div id="test" style="border:1px solid; width:400px; background:#CCCCCC;">
<p>我是拖拽示例DIV。</p>
<p>可以试验一下效果。</p>
</div>
</body>
</html>
阅读(846) | 评论(0) | 转发(0) |