Mobile-side drag (modular development, touch events, Webpack)

Source: Internet
Author: User

The CP end can be easily dragged by jquery. But on the mobile side it's not good. So I wrote a drag-and-drop demo on the mobile side, with the main events being touch events (Touchstart,touchmove and Touchend).

The function of this demo is: the element that can be dragged (here is the picture) is in the list, these elements can be dragged to the specified area (console), after the element is inserted into the console, the original drag element is returned to the original position, the new element can still be dragged in the console, also can drag out the console.

In this demo one uses three modules, namely AJAX module, drag module, position module. Ajax modules are used to implement AJAX requests (so the image resources are obtained through AJAX requests), the drag module is used to implement the element drag-and-drop, and the position module is used to implement the operation of the element position (such as position initialization, restoration, removal). The entry file for the demo is indx.js and the previous three module files are saved in the same folder. After the encoding is complete, it is packaged by Webpack. The development code is in the app folder, and the packaged code is in the build folder.

I. Introduction TO TOUCH Events

There are three touch events, namely Touchstart,touchmove and Touchend. The Touchstart event is triggered when the finger touches the screen. Touchmove a continuous trigger when the finger is sliding on the screen. You can organize page scrolling by canceling its default during this event. The touchend is triggered when the finger leaves the screen. The event objects for these three touch events, in addition to the common properties of mouse events, contain the following three properties:

Touches: Represents an array of touch objects that are currently tracked by touching operations.

Targettouches: An array of touch objects that are specific to the event target.

Changetouches: An array of touch objects that represent what has changed since the last touch.

In this case you need to get the position of the touch point relative to the viewport, I'm using Event.targettouches[0].clientx and Event.targettouches[0].clienty

Two. code for the Ajax module
1 var $ = require (' jquery '); 2  3 var ajax = {4     //Get the initial list of draggable pictures 5     getinitimg:function (parent) {6         var num  =; 7         $.ajax ({8
   
    type: "GET", 9             async:false,//here using synchronous loading, because to let the picture loading completed before you can do other operations             URL: '/home/picwall/index ',             success: function (Result) {                 result.status = 1) {                     $.each (result.data, function (index,item) {+                         var src = Item.pic_src;15                         var width = parseint (item.width);                         var height = parseint (item.height);                         var ratio = Num/height;18                         var img = $ ('
   
'). attr ("src", src). Height (num). Width (parseint (width * ratio));                         parent.append (IMG);                     );                 }22             },23             dataType: ' json '         );     }26};27 module.exports  = ajax;//exposing AJAX modules
Three. code for the position module
  1 var $ = require (' jquery '); 2 3 var position = {4//Initialize position, gap is an object representing the spacing of elements 5 init:function (PARENT,GAP) {6 var Dragelem = parent.c  Hildren (); 7 8//Ensure that the parent element is relative to position 9 if (parent.css (' position ')!== "relative") {Ten parent.css (' position ', ' rel Ative '); One} parent.css ({' width ': ' 100% ', ' z-index ': ' 10 ' 15}); 16//The width of the current list content of var listwidth = 0; 18 19//In the first few columns of var j = 0;             Dragelem.each (function (Index,elem) {$ var Curele = $ (elem); 23 24//Set the initial position of the element 25 Curele.css ({position: "absolute", top:gap. Y, Left:listwidth + gap. X 29}); 30 31//Add a unique identifier for each element, which is useful when restoring the initial position of curele.attr (' Index ', index); 33 34//Save the initial position of the element in Position.coord.push ({x:listwidth + gap.           X, 37      Y:gap. Y 38}); (j) 40 41//Set the parent element's height to Parent.height (parseint (curele.css (' top)) + curele.height () + gap. Y); ListWidth = Curele.offset (). Left + curele.width (); 45});  46}, 47//Insert child element into parent element Addto:function (child,parent,target) {49//parent element at the viewport coordinates var Parentpos = {Wuyi X:parent.offset (). Left, Y:parent.offset (). Top 53}; 54 55//target position relative to viewport coordinates of var Targetpos = {X:target.offset (). Left, Y:target. Offset (). Top 59};                 60 61//Ensure that the parent element is relative to the positioning of the IF (parent.css (' position ')!== "relative") {Parent.css ({64 ' Position ': ' relative ' 65}); Parent.css ({z-index ': ' 12 ' 70}) 71//Insert child element into parent element parent.append (children); 73 74//determines the position of the child element within the parent element and guarantees the size of the child element Child.css ({76 Position:absolute, Top:targetpos.y-parentpos.y, left:targetpos.x-parentpos.x, 7 9 Width:target.width (), Height:target.height () 81}); 82 83}, 84//restores the element to its original position. Restore:function (Elem) {86//Get the identification of the element. var index = parseint (el Em.attr (' index ')); Elem.css ({top:position.coord[index). Y, Left:position.coord[index]. X 91}); 92 93}, 94//The initial coordinate of the dragged element coord:[], 96//Determine if element A is within the range of element B israng:function (Control,draglistpar, $tar             Get) {98 var issituate = undefined; (Control.offset (). Top > Draglistpar.offset (). top) {100  Issituate = $target. Offset (). Top > Control.offset (). top101 && $target. Offset (). Left > Control.offset (). left102 && ($target. Offset (). Left + $target. Width ()) < (control. Offset (). Left + control.width ()); 1}else{104 issituate = ($target. Offset (). Top + $target. Height ()) < (Control.offset (). Top + control.                         Height ()) && $target. Offset () Top > Control.offset (). top106 && $target. Offset (). Left > Control.offset (). left107 && ($target. Offset (). + $target. Width ()) < (Control.offset (). Left + control.width ()); 108}109 return issituate;110}111} ; module.exports = position;

Four. Code for the Drag module
  1 var $ = require (' jquery ');  2 var position = require ('./position.js '); 3 4 var drag = {5//Drag element's parent element ID 6 dragparen:undefined, 7//console ID value 8 control:undefined, 9//Mobile     The position of the block relative viewport is position:{x:undefined, y:undefined 13}, 14//Touch point relative to the location of the viewport, and will be constantly updated during the sliding process 15         touchpos:{x:undefined, y:undefined 18}, 19//Touch point position relative to viewport at start of touch starttouchpos:{21 x:undefined, y:undefined 23}, 24//Touch point relative to the position of the moving block touchoffsetpos:{-x:undefined, Y:undefined 28}, 29//Gets the value of the parent element ID and console ID of the drag element, Setid:function (Draglist,control) {this.dr Agparent = draglist; This.control = control; Touchstart:function (e) {$ var target = E.target; 36 37//block bubble up to E.stoppropagat Ion (); 39 40//block browser default zoom and scroll E.preventdefault (); The var $target = $ (target); 44 45//When the finger just touches the screen, the position of the touch point is drag.starttouchpos.x = E.targettouches[0].clientx; Drag.starttouchpos.y = E.targettouches[0].clienty; 48 49//The position of the touch element relative to the viewport drag.position.x = $target. Offset (). Left; Wuyi DRAG.POSITION.Y = $target. Offset (). Top; 52 53//Touch point relative to the location of the viewport, the sliding process constantly updated drag.touchpos.x = E.targettouches[0].clientx; Drag.touchpos.y = E.targettouches[0].clienty; 56 57//Touch point relative to the position of the touch element drag.touchoffsetpos.x = drag.touchpos.x-drag.position.x; Drag.touchoffsetpos.y = DRAG.TOUCHPOS.Y-DRAG.POSITION.Y; 60 61//Bind the Touchmove event to the target element $target. Unbind (' Touchmove '). On (' Touchmove ', drag.touchmove); +-Touchmove:function (e) {$-var target = E.target; 68 69//Block Bubble-E.stopp Ropagation (); 71 72//block browser default zoom and scroll E.preventdefault (); The $ var $target = $ (target); 76 77//Get the location of the touch point drag.touchpos.x = E.targettoucHes[0].clientx; Drag.touchpos.y = E.targettouches[0].clienty;             80 81//Modify the position of the moving block $target. Offset ({TOP:DRAG.TOUCHPOS.Y-DRAG.TOUCHOFFSETPOS.Y, 84 Left:drag.touchpos.x-drag.touchoffsetpos.x 85}); 86 87//Bind the Touchend event to the moving element $target. Unbind (' Touchend '). On (' Touchend ', drag.touchend); Touchend:function (e) {$ var target = E.target; 92 93//block bubbling 94 E.stoppropagati On (); 95 96//Block browser default zoom and scroll E.preventdefault ();         98: var $target = $ (target), var parent = $target. Parent (); 101 102//Get the console and drag the element list of the parents element 103 var control = $ ("#" + Drag.control); 104 var Draglistpar = $ (' # ' + drag.dragparent); 105 106//Drag element is located in         Console 107 var Sitcontrol = Position.israng (Control, Draglistpar, $target); 108 109//After dragging, if the parent element of the dragged element is a drag-and-drop list 110 if (parent.attr (' id ') = = = = Drag.dragparent) {111//If the element is in a controlledSystem Sitcontrol {113 var dragchild = $target. Clone (); 114 115//bind to the cloned element Touchstart event Dragchild.unbind (' Touchstart '). On (' Touchstart ', Drag.touchstart); 117 118// Insert the cloned elements into the console 119 position.addto (Dragchild, control, $target); 120}121 122//Will the original touch The element reverts to the initial position 123 Position.restore ($target); 124}125 126//After the drag is finished, if the parent element of the dragged element is the console, and the element is dragged out of the console         127 if (parent.attr (' id ') = = = Drag.control &&!sitcontrol) {$target. Remove (); 129 }130}131};132 module.exports = drag;

Five. 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 ');//drag elements horizontally, vertical pitch var gap = {    x:20,    y:10};// Get the list of draggable elements via Ajax ajax.getinitimg (draglist);//Initialize the position of the dragged element Position.init (DRAGLIST,GAP);//Set the height of the console. The height of the console is the height of the screen minus the cap of the drag list var control = $ (' #control '); Control.height ($ (window). Height ()-draglist.height ());// Bind the Touchstart event to each drag element var Dragelem = Draglist.children ();d Ragelem.each (function (Index,elem) {    $ (elem). Unbind (' Touchstart '). On (' Touchstart ', Drag.touchstart);}); The ID value of the parent element of the drag element is Draglist, and the ID value of the operator station is Controldrag.setid (' draglist ', ' control ');

Six. Webpack Packaging

The above uses the idea of modular programming, the different functions are written in different modules, need to use what function can be introduced with require (), but the browser does not have the definition of require method. So the above code does not run directly in the browser and needs to be packaged first. If you're not familiar with Webpack, you can check out this article, Webpack's configuration file is as follows:

var autohtml = require (' Html-webpack-plugin '); var webpack = require (' Webpack '); var extracttextwebpack = require (' Extract-text-webpack-plugin ');//This plugin can separate the CSS file, for the CSS file in a separate file 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: "Drag",            filename: "drag.html",            Template: './app/darg.html '            ), Inject:true        })    ]};

Category: JavaScript demo

Mobile-side drag (modular development, touch events, Webpack)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.