Home > Article > Web Front-end > jQuery mobile drag and drop (modular development, touch events, webpack)
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模块暴露出来
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;
4. Drag module code
var $ = require('jquery'); var position = require('./position.js'); 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('touchmove').on('touchmove',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('touchend').on('touchend',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 = $('#' + drag.dragParent); //拖动元素是否位于控制台 var sitControl = position.isRang(control, dragListPar, $target); //拖动结束后,如果拖拽元素的父元素是拖拽列表 if (parent.attr('id') === drag.dragParent) { //如果元素位于控制台 if (sitControl) { var dragChild = $target.clone(); //为克隆出的元素绑定touchstart事件 dragChild.unbind('touchstart').on('touchstart',drag.touchStart); //将克隆出的元素插入到控制台 position.addTo(dragChild, control, $target); } //将原来的触摸元素恢复到初始位置 position.restore($target); } // 拖拽结束后,如果拖拽元素的父元素是控制台,并且元素拖出了控制台 if (parent.attr('id') === drag.control && !sitControl) { $target.remove(); } } }; module.exports = drag;
5. Entry file index.js code
require('../css/base.css'); require('../css/drag.css'); var $ = require('jquery'); var drag = require('./drag.js'); var position = require('./position.js'); var ajax = require('./ajax.js'); var dragList = $('#dragList'); //可拖拽元素的水平,竖直间距 var gap = { X:20, Y:10 }; //通过ajax获取可拖拽的元素的列表 ajax.getInitImg(dragList); //初始化可拖拽元素的位置 position.init(dragList,gap); //设置控制台的高度。控制台的高度为屏幕的高度减去拖拽列表的盖度 var control = $('#control'); control.height( $(window).height() - dragList.height() ); //给每个拖动元素绑定touchstart事件 var dragElem = dragList.children(); dragElem.each(function(index,elem){ $(elem).unbind('touchstart').on('touchstart',drag.touchStart); }); //拖拽元素的父元素的id值为dragList,操作台的id值为control drag.setID('dragList','control');
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('html-webpack-plugin'); var webpack = require('webpack'); var extractTextWebpack = require('extract-text-webpack-plugin');// 这个插件可以将css文件分离出来,为css文件位于单独的文件中 module.exports = { entry:{ 'index':'./app/js/index.js', 'jquery':['jquery'] }, output:{ path:'./build/', filename:'js/[name].js' }, module:{ loaders:[ { test:/\.css/, loader:extractTextWebpack.extract('style','css') } ] }, plugins:[ new extractTextWebpack('css/[name].css',{ allChunks:true }), new webpack.optimize.CommonsChunkPlugin({ name:'jquery', filename:'js/jquery.js' }), new autoHtml({ title:"拖拽", filename:"drag.html", template:'./app/darg.html', inject:true }) ] };
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!