您的位置:首页 > Web前端 > JQuery

基于jquery的一个简单拖拽功能

2011-09-08 17:49 597 查看
拖拽功能,首先是需要 mousedown,mousemove,mouseup 这三个事件的,然后最主要的是怎么样计算 目标元素 随鼠标移动的坐标 。

1. 在mousedown事件里,获取鼠标点击时的坐标:initPos.x | initPos.y 和 目标元素的坐标: $target.offset().left | $target.offset().top, 计算出 当时鼠标 相对 目标元素左上角的 坐标relPos.x = initPos.x - $target.offset().left , relPosy = initPos.y- $taget.offset().top。

2. 在mousemove 事件里,获取鼠标移动的坐标, event.pageX 和 event.pageY; 目标元素最后的坐标便是: movePos.x = event.pageX - relPos.x; movePos.y = event.pageY- relPos.Y; (这个不理解的画个草图就知道怎么回事了)

3. 在mouseup事件里,停止。

具体的代码如下:

<!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 type="text/css">
body, div { margin: 0; paading: 0; font-size: 12px; }
ul, li { margin: 0; padding: 0; list-style: none; }
.clear { clear: both; width: 1px; height: 0px; line-height: 0px; font-size: 1px; }
.box { width: 960px; margin: 0 auto; padding-top: 15px; }
.bor { width: 100px; height: 80px; margin: 12px; padding: 10px; border: 1px solid #ccc; background: #ececec; }

</style>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
var move = false; // 移动状态
var zIndexCount = 0; // css 中 z-index标识
var $bor = $(".bor"), target = null, goal = null;
var initPos = {x: 0, y: 0}, relPos = {x: 0, y: 0}, movePos = {x: 0, y: 0};
// 初始坐标 和 拖拽最后的位置坐标 也可以这样设置 var initX = 0, initY = 0, rX = 0, rY = 0;
var borCount = $bor.length;
$bor.each(function() {

$(this).mousedown(function(event) {
$target = $(this);

// 鼠标点击的初始位置
initPos.x = event.pageX;
initPos.y = event.pageY;

goal = $bor.eq($target.index())
// 鼠标点击时 相对 目标元素左上角的位置。
relPos.x = initPos.x - $target.offset().left;
relPos.y = initPos.y - $target.offset().top;

move = true;

zIndexCount++;
$target.css({ position: "absolute", zIndex: zIndexCount });
});

$(document).mousemove(function(event) {
if(move) {
//目标元素新的坐标。
movePos.x = event.pageX - relPos.x;
movePos.y = event.pageY - relPos.y;

goal.css({ left: movePos.x + "px", top: movePos.y + "px" });

}
}).mouseup(function() {
move = false;
});

});

});

</script>
</head>

<body>
<div class="box">

<div class="bor">box1</div>
<div class="bor">box2</div>
<div class="bor">box3</div>
<div class="bor">box4</div>
<div class="bor">box5</div>
<div class="clear"></div>
</div>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: