西狐网logo

用jQuery轻松实现Div拖动

用jQuery轻松实现Div拖动,只需只行代码,很简单. 试试效果:
hooyes
代码:
<!DOCTYPE html>
<html>
<head>
<title>hooyes Drag demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
type
="text/javascript"></script>
<style type="text/css">
.drag
{
position
:absolute;
width
:100px; height:100px;
border
:1px solid #96C2F1; background-color: #EFF7FF;
cursor
:move; line-height:100px; text-align:center;
}
</style>
<script type="text/javascript">
(
function (document) {
//Usage: $("#id").drag()
//Author: hooyes
$.fn.Drag = function () {
var M = false;
var Rx, Ry;
var t = $(this);
t.mousedown(
function (event) {
Rx
= event.pageX - (parseInt(t.css("left")) || 0);
Ry
= event.pageY - (parseInt(t.css("top")) || 0);
t.css(
"position", "absolute").css('cursor', 'move').fadeTo(20, 0.5);
M
= true;
})
.mouseup(
function (event) {
M
= false; t.fadeTo(20, 1);
});
$(document).mousemove(
function (event) {
if (M) {
t.css({ top: event.pageY
- Ry, left: event.pageX - Rx });
}
});
}
})(document);


$(document).ready(
function () {
$(
"#Div1").Drag();
});
</script>
</head>
<body>
<div id="Div1" class="drag">hooyes</div>
</body>
</html>

posted on 2011-05-20 14:43  西狐  阅读(3184)  评论(1编辑  收藏  举报

导航