PHP+jQuery实现随意拖动层并即时保存拖动位置_jquery
想拖动页面上的层,完全可以用jQuery ui的Draggable方法来实现,那如何将拖动后层的位置保存下来呢?本文将给出答案。本文讲解了如何采用PHP+MySQL+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现在在p中。
<?php echo $notes;?>
注意,我在生成的每个DIV.note中定义了位置,即设置该p的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。
PHP之友评论