php+mysql+jquery实现拖动并保存拖动层位置
想拖动页面上的层,完全可以用jquery ui的draggable方法来实现,那如何将拖动后层的位置保存下来呢?本文将给出答案。本文讲解了如何采用php+mysql+jquery,实现随意拖动层并即时保存拖动位置。 之前...
想拖动页面上的层,完全可以用jquery ui的draggable方法来实现,那如何将拖动后层的位置保存下来呢?本文将给出答案。本文讲解了如何采用php+mysql+jquery,实现随意拖动层并即时保存拖动位置。
之前我有文章:jquery实现拖动布局并将排序结果保存到数据库,文中以项目为示例,讲解了实现拖动布局的方法。本文与之不同之处在于可以任意拖动
页面位置,原理就是通过拖动将拖动后层的相对位置left,top和z-index三个参数更新到数据表中对应的记录,页面通过css解析每个层不同的位
置。请看具体实现步骤。
准备mysql数据表
首先需要准备一张表notes,用来记录层的内容,背景色和坐标等信息。
create table if not exists `notes` (`id` int(11) not null auto_increment,`content` varchar(200) not null,`color` enum('yellow','blue','green') not null default 'yellow',`xyz` varchar(100) default null,primary key (`id`)) engine=myisam default charset=utf8
然后向表中插入几条记录,注意xyz字段表示的是层的xyz坐标的组合,格式为x|y|z。
drag.php
在drag.php中,需要读取notes表中的记录,显示在drag.php页面中,代码如下:
include_once('connect.php'); //链接数据库$notes = ''; $left=''; $top=''; $zindex=''; $query = mysql_query(select * from notes order by id desc);while($row=mysql_fetch_array($query)){ list($left,$top,$zindex) = explode('|',$row['xyz']); $notes.= ' '.$row['id'].'.'.htmlspecialchars($row['content']).'
';}
然后将读取出来的$notes现在在div中。
注意,我在生成的每个div.note中定义了位置,即设置该div的left,top和z-index值。
css
.demo{position:relative; height:500px; margin:20px; border:1px dotted #d3d3d3}.note{width:150px; height:150px; position:absolute; margin-top:150px; padding:10px; overflow:hidden; cursor:move; font-size:16px; line-height:22px;}.note span{margin:2px} .yellow{background-color:#fdfb8c;border:1px solid #dedc65;}.blue{background-color:#a6e3fc;border:1px solid #75c5e7;}.green{background-color:#a5f88b;border:1px solid #98e775;}
有了样式之后,然后运行drag.php,这时就可以看到页面中排列的的几个层,但是还不能拖动,因为还要加入jquery。
jquery
首先需要载入jquery库和jquery-ui插件以及global.js。
然后再global.js加入代码:
$(function(){var tmp;$('.note').each(function(){tmp = $(this).css('z-index');if(tmp>zindex) zindex = tmp;})make_draggable($('.note'));});var zindex = 0;
global.js中,首先在$(function()里定义了一个变量tmp,通过判断每个div.note的z-index值,保证拖动时,该div在最上层(即z-index为最大值),就是不会被别的层覆盖。
并且设置zindex的初始值为0。
接下来,写了一个函数make_draggable();该函数调用jquery ui插件的draggable方法,处理拖动范围,透明度及拖动停止后执行的更新操作。
function make_draggable(elements){elements.draggable({opacity: 0.8,containment:'parent',start:function(e,ui){ ui.helper.css('z-index',++zindex); },stop:function(e,ui){$.get('update_position.php',{x : ui.position.left,y : ui.position.top,z : zindex,id : parseint(ui.helper.find('span.data').html())});}});}
当拖动时,将当前层的z-index属性设置为最大值,即保证当前层在最上面,不被其他层覆盖,并且设置了拖动范围和透明度,当停止拖动时,向后台
update_position.php发送一个ajax请求,传递的参数有x,y,z和id的值。接下来我们来看
update_position.php的处理。
update_position.php保存拖动位置
update_position.php需要做的是,获取前台通过ajax请求发来的数据,更新数据表中相应的字段内容。
include_once('connect.php');if(!is_numeric($_get['id']) || !is_numeric($_get['x']) || !is_numeric($_get['y']) ||!is_numeric($_get['z']))die(0);$id = intval($_get['id']);$x = intval($_get['x']);$y = intval($_get['y']);$z = intval($_get['z']);mysql_query(update notes set xyz='.$x.|.$y.|.$z.' where id=.$id);echo 1;