本文实例讲述了jQuery实现的简单拖拽功能。分享给大家供大家参考,具体如下:<!doctypehtm
本文实例讲述了jQuery实现的简单拖拽功能。分享给大家供大家参考,具体如下:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>www.jb51.net jQuery拖拽</title>
<style type="text/css">
#box{
position:fixed;
left:100px;
top:100px;
background-color:red;
width:300px;
height:200px;
}
#out{
height:2000px;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var drafting=false;
var offX,offY,mouseX,mouseY,winX,winY,x,y;
$("#box").mousedown(function(event){
event.stopPropagation();
drafting=true;
});
$(document).mousemove(function(event){
event.stopPropagation();
var e=event||window.event;
mouseX=e.pageX||e.clientX+$(document).scrollLeft();
mouseY=e.pageY||e.clientY+$(document).scrollTop();
winX=$("#box").offset().left-$(document).scrollLeft();
winY=$("#box").offset().top-$(document).scrollTop();
if(drafting==false){
offX=mouseX-winX;
offY=mouseY-winY;
}
x=mouseX-offX;
y=mouseY-offY;
$("#box").css({'left':x,'top':y});
});
$(document).mouseup(function(event){
event.stopPropagation();
drafting=false;
});
});
</script>
</head>
<body>
<div id="box"></div>
<div id="out"></div>
</body>
</html>
这里使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun,可得到如下测试效果:
jQuery 拖拽