Home Web Front-end JS Tutorial jQuery mobile drag and drop (modular development, touch events, webpack)

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

Jan 04, 2017 pm 02:16 PM

Drag and drop on the CP side can be easily achieved 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 elements that can be dragged (here are pictures) are in the list. These elements can be dragged to the specified area. After reaching the specified area (console), the elements are inserted into the control After the console, the original dragged element returns to its original position, and the new element 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 the common properties of mouse events, the event objects of these three touch events also include the following three properties:

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 that represents 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 use event.targetTouches[0].clientX and event.targetTouches[0].clientY

二.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

3. Position module code

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

4. Drag module code

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

5. Entry file index.js code

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

6.webpack packaging

The above uses the idea of ​​modular programming, and writes different functional implementations in different modules. You can use require() to introduce whatever functions you need, but browsing The container does not have a require method defined. 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

The above is the jQuery mobile drag and drop (modular development, touch event) introduced by the editor , webpack), I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more jQuery mobile drag and drop (modular development, touch events, webpack) related articles, please pay attention to the PHP Chinese website!


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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1271
29
C# Tutorial
1251
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles