Home php教程 PHP开发 jQuery mobile drag and drop (modular development, touch events, webpack)

jQuery mobile drag and drop (modular development, touch events, webpack)

Dec 08, 2016 pm 02:06 PM
jquery

CP-side drag and drop can be easily implemented through jquery. But it doesn’t work well on the mobile side. So I wrote a drag and drop demo on the mobile terminal. The main events used are touch events (touchstart, touchmove and touchend).

The function implemented by this demo is: the draggable elements (pictures in this case) are in the list. These elements can be dragged to the specified area. After reaching the specified area (console), after the elements are inserted into the console, the original The dragged element returns to its original position, and new elements can still be dragged in the console or out of the console.

In this demo, three modules are used, namely ajax module, drag module and position module. The ajax module is used to implement ajax requests (all image resources are obtained through ajax requests), the drag module is used to implement element dragging, and the position module is used to implement element position operations (such as position initialization, restoration, removal). The entry file of the demo is indx.js and the previous three module files are saved in the same folder. After coding is completed, it is packaged through webpack. The development code is located in the app folder, and the packaged code is located in the build folder.

1. Introduction to touch events

There are three touch events, namely touchstart, touchmove and touchend. The touchstart event is triggered when a finger touches the screen. touchmove fires continuously when a finger slides across the screen. Deactivating this event during its occurrence prevents page scrolling. touchend is triggered when the finger is lifted off the screen. In addition to providing common attributes of mouse events, the event objects of these three touch events also include the following three attributes:

  Touches: An array of touch objects representing the currently tracked touch operations.

 targetTouches: An array of Touch objects specific to the event target.

 changeTouches: An array of Touch objects indicating what has changed since the last touch.

In this case, I need to get the position of the touch point relative to the viewport. I am using event.targetTouches[0].clientX and event.targetTouches[0].clientY

Second.ajax module code

var $ = require('jquery');
var ajax = {
//得到可拖拽图片的初始列表
getInitImg:function(parent){
var num = 50;
$.ajax({
type:"GET",
async:false,//这里使用同步加载,因为要让图片加载完成后才能做其他操作
url:'/Home/picwall/index',
success:function(result){
if(result.status == 1) {
$.each(result.data, function (index,item) {
var src = item.pic_src;
var width = parseInt(item.width);
var height = parseInt(item.height);
var ratio = num / height;
var img = $('').attr("src",src).height(num).width(parseInt(width * ratio));
parent.append(img);
});
}
},
dataType:'json'
});
}
};
module.exports = ajax;//将ajax模块暴露出来
Copy after login

Three. The code of the position module

var $ = require('jquery');
var position = {
//初始化位置,gap是一个表示元素间距的对象
init:function(parent,gap){
var dragElem = parent.children();
//确保父元素是相对定位
if(parent.css('position') !== "relative"){
parent.css('position','relative');
}
parent.css({
'width':"100%",
'z-index':'10'
});
//当前列表内容的宽度
var ListWidth = 0;
//位于第几列
var j = 0;
dragElem.each(function(index,elem){
var curEle = $(elem);
//设置元素的初始位置
curEle.css({
position:"absolute",
top:gap.Y,
left:ListWidth + gap.X
});
//为每个元素添加一个唯一的标识,在恢复初始位置时有用
curEle.attr('index',index);
//将元素的初始位置保存起来
position.coord.push({
X:ListWidth + gap.X,
Y:gap.Y
});
j++;
//设置父元素的高度
parent.height( parseInt(curEle.css('top')) + curEle.height() + gap.Y);
ListWidth = curEle.offset().left + curEle.width();
});
},
//将子元素插入到父元素中
addTo:function(child,parent,target){
//父元素在视口的坐标
var parentPos = {
X:parent.offset().left,
Y:parent.offset().top
};
//目标位置相对于视口的坐标
var targetPos = {
X:target.offset().left,
Y:target.offset().top
};
//确保父元素是相对定位
if(parent.css('position') !== "relative"){
parent.css({
'position':'relative'
});
}
parent.css({
'z-index':'12'
});
//将子元素插入父元素中
parent.append(child);
//确定子元素在父元素中的位置并且保证子元素的大小不变
child.css({
       position:absolute,
top:targetPos.Y - parentPos.Y,
left:targetPos.X - parentPos.X,
width:target.width(),
height:target.height()
});
},
//将元素恢复到原来的位置
restore:function(elem){
//获得元素的标识
var index = parseInt( elem.attr('index') );
elem.css({
top:position.coord[index].Y,
left:position.coord[index].X
});
},
//拖拽元素的初始坐标
coord:[],
//判断元素A是否在元素B的范围内
isRang:function(control,dragListPar,$target){
var isSituate = undefined;
if(control.offset().top > dragListPar.offset().top){
isSituate = $target.offset().top > control.offset().top
&& $target.offset().left > control.offset().left
&& ($target.offset().left + $target.width()) < (control.offset().left + control.width());
}else{
isSituate = ($target.offset().top + $target.height())<(control.offset().top + control.height())
&& $target.offset().top > control.offset().top
&& $target.offset().left > control.offset().left
&& ($target.offset().left + $target.width()) < (control.offset().left + control.width());
}
return isSituate;
}
};
module.exports = position;
Copy after login

Four. The code of the drag module

var $ = require(&#39;jquery&#39;);
var position = require(&#39;./position.js&#39;);
var drag = {
//拖拽元素的父元素的id
dragParen:undefined,
//操作台的id值
control:undefined,
//移动块相对视口的位置
position:{
X:undefined,
Y:undefined
},
//触摸点相对视口的位置,在滑动过程中会不断更新
touchPos:{
X:undefined,
Y:undefined
},
//开始触摸时触摸点相对视口的位置
startTouchPos:{
X:undefined,
Y:undefined
},
//触摸点相对于移动块的位置
touchOffsetPos:{
X:undefined,
Y:undefined
},
//获取拖拽元素父元素id和控制台的ID的值
setID:function(dragList,control){
this.dragParent = dragList;
this.control = control;
},
touchStart:function(e){
var target = e.target;
//阻止冒泡
e.stopPropagation();
//阻止浏览器默认的缩放和滚动
e.preventDefault();
var $target = $(target);
//手指刚触摸到屏幕上时,触摸点的位置
drag.startTouchPos.X = e.targetTouches[0].clientX;
drag.startTouchPos.Y = e.targetTouches[0].clientY;
//触摸元素相对视口的位置
drag.position.X = $target.offset().left;
drag.position.Y = $target.offset().top;
//触摸点相对于视口的位置,滑动过程中不断更新
drag.touchPos.X = e.targetTouches[0].clientX;
drag.touchPos.Y = e.targetTouches[0].clientY;
//触摸点相对于触摸元素的位置
drag.touchOffsetPos.X = drag.touchPos.X - drag.position.X;
drag.touchOffsetPos.Y = drag.touchPos.Y - drag.position.Y;
//给目标元素绑定touchMove事件
$target.unbind(&#39;touchmove&#39;).on(&#39;touchmove&#39;,drag.touchMove);
},
touchMove:function(e){
var target = e.target;
//阻止冒泡
e.stopPropagation();
//阻止浏览器默认的缩放和滚动
e.preventDefault();
var $target = $(target);
//获得触摸点的位置
drag.touchPos.X = e.targetTouches[0].clientX;
drag.touchPos.Y = e.targetTouches[0].clientY;
//修改移动块的位置
$target.offset({
top: drag.touchPos.Y - drag.touchOffsetPos.Y,
left: drag.touchPos.X - drag.touchOffsetPos.X
});
//给移动元素绑定touchend事件
$target.unbind(&#39;touchend&#39;).on(&#39;touchend&#39;,drag.touchEnd);
},
touchEnd:function(e) {
var target = e.target;
//阻止冒泡
e.stopPropagation();
//阻止浏览器默认的缩放和滚动
e.preventDefault();
var $target = $(target);
var parent = $target.parent();
//得到控制台和拖动元素列表的父元素
var control = $("#" + drag.control);
var dragListPar = $(&#39;#&#39; + drag.dragParent);
//拖动元素是否位于控制台
var sitControl = position.isRang(control, dragListPar, $target);
//拖动结束后,如果拖拽元素的父元素是拖拽列表
if (parent.attr(&#39;id&#39;) === drag.dragParent) {
//如果元素位于控制台
if (sitControl) {
var dragChild = $target.clone();
//为克隆出的元素绑定touchstart事件
dragChild.unbind(&#39;touchstart&#39;).on(&#39;touchstart&#39;,drag.touchStart);
//将克隆出的元素插入到控制台
position.addTo(dragChild, control, $target);
}
//将原来的触摸元素恢复到初始位置
position.restore($target);
}
// 拖拽结束后,如果拖拽元素的父元素是控制台,并且元素拖出了控制台
if (parent.attr(&#39;id&#39;) === drag.control && !sitControl) {
$target.remove();
}
}
};
module.exports = drag;
Copy after login

Five. The code of the entry file index.js

require(&#39;../css/base.css&#39;);
require(&#39;../css/drag.css&#39;);
var $ = require(&#39;jquery&#39;);
var drag = require(&#39;./drag.js&#39;);
var position = require(&#39;./position.js&#39;);
var ajax = require(&#39;./ajax.js&#39;);
var dragList = $(&#39;#dragList&#39;);
//可拖拽元素的水平,竖直间距
var gap = {
X:20,
Y:10
};
//通过ajax获取可拖拽的元素的列表
ajax.getInitImg(dragList);
//初始化可拖拽元素的位置
position.init(dragList,gap);
//设置控制台的高度。控制台的高度为屏幕的高度减去拖拽列表的盖度
var control = $(&#39;#control&#39;);
control.height( $(window).height() - dragList.height() );
//给每个拖动元素绑定touchstart事件
var dragElem = dragList.children();
dragElem.each(function(index,elem){
$(elem).unbind(&#39;touchstart&#39;).on(&#39;touchstart&#39;,drag.touchStart);
});
//拖拽元素的父元素的id值为dragList,操作台的id值为control
drag.setID(&#39;dragList&#39;,&#39;control&#39;);
Copy after login

Six .webpack packaging

The idea of ​​modular programming is used above, and different functional implementations are written in different modules. You can use require() to introduce any functions you need, but the browser does not have a definition of the require method. Therefore, the above code cannot be run directly in the browser and needs to be packaged first. If you are not familiar with webpack, you can check this article. The configuration file of webpack is as follows:

var autoHtml = require(&#39;html-webpack-plugin&#39;);
var webpack = require(&#39;webpack&#39;);
var extractTextWebpack = require(&#39;extract-text-webpack-plugin&#39;);// 这个插件可以将css文件分离出来,为css文件位于单独的文件中
module.exports = {
entry:{
&#39;index&#39;:&#39;./app/js/index.js&#39;,
&#39;jquery&#39;:[&#39;jquery&#39;]
},
output:{
path:&#39;./build/&#39;,
filename:&#39;js/[name].js&#39;
},
module:{
loaders:[
{
test:/\.css/,
loader:extractTextWebpack.extract(&#39;style&#39;,&#39;css&#39;)
}
]
},
plugins:[
new extractTextWebpack(&#39;css/[name].css&#39;,{
allChunks:true
}),
new webpack.optimize.CommonsChunkPlugin({
name:&#39;jquery&#39;,
filename:&#39;js/jquery.js&#39;
}),
new autoHtml({
title:"拖拽",
filename:"drag.html",
template:&#39;./app/darg.html&#39;,
inject:true
})
]
};
Copy after login


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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles