Home Web Front-end JS Tutorial PHP jQuery realizes dragging layers at will and saving the drag position instantly_jquery

PHP jQuery realizes dragging layers at will and saving the drag position instantly_jquery

May 16, 2016 pm 04:01 PM
jquery php

If you want to drag a layer on the page, you can completely use the Draggable method of jQuery ui. So how to save the position of the layer after dragging? This article will give the answer. This article explains how to use PHP MySQL jQuery to drag layers at will and save the drag position instantly.

I had an article before: In the article, I explained the method of implementing drag layout using the project as an example. The difference between this article and this article is that you can drag the page position arbitrarily. The principle is to update the relative position left, top and z-index of the dragged layer to the corresponding record in the data table through dragging. The page is parsed through CSS. Different locations for each layer. Please see the specific implementation steps.

Prepare MySQL data table

First, you need to prepare a table notes to record the layer content, background color, coordinates and other information.

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; 
Copy after login

Then insert several records into the table. Note that the xyz field represents the combination of the xyz coordinates of the layer, in the format of "x|y|z".

drag.php

In drag.php, you need to read the records in the notes table and display them in the drag.php page. The code is as follows:

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.= ' 
  <div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:' 
.$zindex.'"> 
    <span class="data">'.$row['id'].'.</span>'.htmlspecialchars($row['content']).' 
  </div>'; 
} 
Copy after login

Then the read $notes will now be in the div.

<div class="demo"> 
  <&#63;php echo $notes;&#63;> 
</div> 
Copy after login

Note that I define the position in each DIV.note generated, that is, set the left, top and z-index values ​​​​of the div.

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;} 
Copy after login

After you have the style, run drag.php. At this time, you can see several layers arranged on the page, but you cannot drag them yet because jQuery needs to be added.

jQuery

First you need to load the jquery library, jquery-ui plug-in and global.js.

<script type="text/javascript" src="js/jquery.js"></script> 
<script type="text/javascript" src="js/jquery-ui.min.js"></script> 
Copy after login


Then add the code to global.js:

$(function(){ 
  var tmp; 
   
  $('.note').each(function(){ 
    tmp = $(this).css('z-index'); 
    if(tmp>zIndex) zIndex = tmp; 
  }) 
  make_draggable($('.note')); 
}); 
var zIndex = 0; 
Copy after login

In global.js, a variable tmp is first defined in $(function()). By judging the z-index value of each div.note, it is ensured that the DIV is at the top level (i.e. z-index) when dragging. is the maximum value), that is, it will not be covered by other layers
. And set the initial value of zIndex to 0.
Next, I wrote a function make_draggable(); this function calls the Draggable method of the jquery ui plug-in to handle the drag range, transparency, and update operations performed after the drag stops.

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()) 
      }); 
    } 
  }); 
} 
Copy after login

When dragging, set the z-index attribute of the current layer to the maximum value, that is, ensure that the current layer is at the top and not covered by other layers, and set the drag range and transparency. When you stop dragging, Send an ajax request to the background update_position.php, passing the parameters x, y, z and id values. Next let's look at the processing of update_position.php.
update_position.php saves the drag position
What update_position.php needs to do is to obtain the data sent by the front desk through ajax request and update the corresponding field contents in the data table.

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"; 
Copy after login

The above is the entire content of this article, I hope you all like it.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles