H5 Case sharing: Mobile slide-screen Touch Event

Source: Internet
Author: User
Tags abs

Mobile Swipe Touch Event

The effect of mobile touch screen sliding effect on electronic devices has been applied more and more widely, similar to the PC-side picture carousel, but on mobile devices, to achieve this effect of the carousel, you need to use the core touch events. Handle touch events to track each finger to the screen slide.

Here are four kinds of touch events

Touchstart: Triggers when the screen is touched, even if a finger has been placed on the screen.
Touchmove://continuous trigger when sliding on the screen. During this event, calling Preventdefault () can prevent scrolling.
Touchend://triggers when removed from the screen.
Touchcancel://The system cancels the touch event when triggered, this seems to be less use.
The above events will be bubbling and can be canceled. Although these touch events are not defined in the DOM specification, they are implemented in a way that is compatible with the DOM. Therefore, each touch event is not defined in the DOM specification, but they are implemented in a way that is compatible with the DOM. Therefore, the event object for each touch event provides properties that are common in mouse events: Bubbles, cancelable, view, ClientX, ClientY, ScreenX, ScreenY, detail, Altkey, Shiftkey, Ctrlkey and Metakey.

Once each touch event is triggered, an event object is generated, with an additional three touch lists included in the event object.
The touches://represents an array of touch objects that are currently tracked by touching operations.
When a finger is on the touch screen, event.touches.length=1,
When two fingers are on the touchscreen, event.touches.length=2, etc.
targettouches://an array of touch objects specific to the event target. Because the touch event is bubbling, this attribute is used to indicate the target object.
changedtouches://represents an array of touch objects that have changed since the last touch.

Each touch in these lists consists of the touch object, which contains the touching information, with the following main attributes:
clientx://Touch the x-coordinate of the target in the viewport.
clienty://Touch the y-coordinate of the target in the viewport.
IDENTIFIER://identifies the unique ID of the touch.
pagex://Touch the x-coordinate of the target in the page.
pagey://Touch the y-coordinate of the target in the page.
screenx://Touch the x-coordinate of the target in the screen.
screeny://Touch the y-coordinate of the target in the screen.
target://touches the DOM node target.

Precautions:

When you swipe the entire screen, your finger affects the browser's behavior, such as scrolling and zooming. So when you invoke the touch event, be careful to suppress zooming and scrolling.

1. Disable zooming

Set with meta meta tags.

<meta name= "viewport" content= "Width=device-width, initial-scale=1, maximum-scale=1,minimum-scale=1, User-scalable=no ">

With this code, the page we're writing will not zoom in and out as the gesture is used.

2. Disable scrolling

Preventdefault is blocking the default behavior, and the default behavior of the touch event is scrolling.
Because touch causes the screen to move, you can use Event.preventdefault () within the event handlers of these events to prevent the default scrolling of the screen.

The method used to write the demo here is to write the HTML structure and pass the arguments to it. It accepts all sliding page objects (in this case, Document.queryselector (' #pages ')) and the direction to be set (with X, y representing landscape or portrait) and an optional extension function.

Portrait Sliding screen case :
Here all the code is encapsulated in a Pageslide prototype object, can be used as a native JS plugin,

The structure of the HTML it requires is:

<div class= "Pages" >
<div class= "Page Page1" >page1</div>
<div class= "Page page2" >page2<div class= "Myanimation" ></div></div>
<div class= "Page Page3" >page3</div>
<div class= "Page page4" >page4</div>
<div class= "Page page5" >page5</div>
<div class= "Page Page6" >page6</div>
</div>

The CSS style structure is :

/* Note Add HTML tags so that height 100% equals window Height */
html,body{width:100%; height:100%; margin:0; padding:0; overflow:hidden;}

/* Uniform style of sliding page */
. pages{width:100%; height:100%; position:relative;}
. page {font-size:100px; position:absolute; top:0; left:0; width:100%; height:100%; overflow:hidden;}

. Page1{background:pink;}
. Page2{background:lightgreen;}
. Page3{background:skyblue;}
. page4{background:red;}
. Page5{background:green;}
. Page6{background:blue;}

/* The Box animation */
. box{width:100px; height:100px; background:black;}

/* All animations use class control */
. play. myanimation{animation:move 1s ease 1 both-webkit-animation:move 1s ease 1 both;}
@-webkit-keyframes move{
100%{
-webkit-transform:translate3d (150px,0,0);
Transform:translate3d (150px,0,0);
-ms-transform:translate3d (150px,0,0);
}
}

The key to achieving a finger-following sliding effect is to set the Transform:translate3d (x, y, z) parameter through the touch event and set a minimum sliding distance of minrange at the end of the slide (touchend), sliding within that distance range, The parameter of the Translate3d is equal to the sliding distance of touchmove, and when it is greater than minrange, the overall slide of the next page (or previous page) is triggered, and the parameter of the Translate3d x or y is the width of the window (when sliding horizontally) or high (when sliding vertically).


In addition, for a single page of a Web page, you also need to solve a problem, that is, each page may have animation or other events to start playing when the page appears, the animation is controlled by the CSS class, which is used in each of the current page to add a. Play class as a marker, in the CSS animation settings for each page, Also add the. Play class name, which allows you to start the animation on this page when it appears.


the code for JavaScript is as follows :

Pageslide receive three parameters: page element, sliding direction to set, optional extension function

var pageslide = function (el, swipe, options) {

this.options = Options | | {}; Optional functions

this.current = 0; Current page Index

This.pagex; Transverse finger Placement

This.pagey; Portrait of the Finger Landing

This.height; Device height

This.width; Device width

This.flag; Variable to determine the direction of the slide

This.move; Distance to Slide

this. $el = El; Object of the current page

This.swipe = Swipe | | ' X '; Sliding direction parameters

This.resize (). Init (). bindevents (); Initialization

}

PageSlide.prototype.init = function (i) {

var current = I? this. $el. Children[i]: this. $el. Firstelementchild;

if (!current) throw ' ERROR ';

The moving class is the marker of the current sliding page, and also the extended effect of sliding in the style.

Current.classList.add (' moving ');

Current.style.webkitTransform = ' Translate3d (0,0,0) ';

Pre-set the width of other pages with swipe values for smooth interaction

for (var i = 1; I <this. $el. children.length; i++) {

this[' Set ' + This.swipe] (this. $el. Children[i], (this.swipe = = = ' X '? this.width:this.height))

};

SetTimeout (function () {

Current.classList.remove (' moving ')

Current.classList.add (' play ')

}, 3e2);

return this

};

Binding functions for binding various events to a page

PageSlide.prototype.bindEvents = function () {

var = this;

Window.addeventlistener (' Resize Orientationchange ', This.resize.bind (this), false);

' Touchstart touchmove touchend touchcancel '. Split ('). ForEach (function (EVN) {

Bind four touch functions (declared at the back) to each page

Self. $el. AddEventListener (EVN, Self[evn].bind (self), false);

});

}

Gets the current touch of the Page object

PageSlide.prototype.getCurrent = function () {

return this. $el. Children[this.current];

};

Get the device's width and height when initializing

PageSlide.prototype.resize = function () {

This.width = this. $el. Parentnode.clientwidth;

This.height = this. $el. parentnode.clientheight;

return this;

};

Random () method to reach any page

PageSlide.prototype.random = function () {

var count = this. $el. children.length;

var current = This.current;

var arr = [];

var num;

for (var i = 0; i < count; i++) {

if (I!== current) Arr.push (i.ToString ())

};

num = Math.floor (math.random () * arr.length);

This.direct (+arr[num]);

}

Four built-in sliding event functions that echo the previous binding function

PageSlide.prototype.touchstart = function (e) {

var touches = e.touches[0];

Touch start

This.flag = null;

This.move = 0;

Record placement

This.pagex = Touches.pagex;

This.pagey = Touches.pagey;

};

PageSlide.prototype.touchmove = function (e) {

var touches = e.touches[0];;

var X = Touches.pagex-this.pagex;

var Y = Touches.pagey-this.pagey;

var current = This.getcurrent ();

var next = current.nextelementsibling;

var prev = current.previouselementsibling;

Add a move style

if (!this.flag) {

This.flag = Math.Abs (X) > Math.Abs (Y)? ' X ': ' Y ';

if (This.flag = = = This.swipe) {

Current.classList.add (' moving ');

Next && next.classList.add (' moving ');

Prev && prev.classList.add (' moving ');

};

};

if (This.flag = = = This.swipe) {

E.preventdefault ();

E.stoppropagation ();

Switch (this.swipe) {

Case ' X ':

Swipe Horizontal

This.move = X;

This.setx (current, X);

Next && (This.setx (Next, X + this.width));

Prev && (This.setx (prev, x-this.width));

Break

Case ' Y ':

Swipe Vertical

This.move = Y;

This.sety (current, Y);

Next && (This.sety (Next, Y + this.height));

Prev && (this.sety (prev, y-this.height));

Break

}

}

}

PageSlide.prototype.touchend = function (e) {

var minrange = 50;

var move = This.move;

var current = This.getcurrent ();

var next = current.nextelementsibling;

var prev = current.previouselementsibling;

Current.classList.remove (' moving ');

Next && next.classList.remove (' moving ');

Prev && prev.classList.remove (' moving ');

if (!this.flag) return;

E.preventdefault ();

Swipe to the end of the page before the next () method calls the Go () method

if (Move <-minrange && next) return This.next ();

if (Move > Minrange && prev) return This.prev ();

This.reset ();

}

PageSlide.prototype.touchcancel = function (e) {

var current = This.getcurrent ();

var next = current.nextelementsibling;

var prev = current.previouselementsibling;

Current.classList.remove (' moving ');

Next && next.classList.remove (' moving ');

Prev && prev.classList.remove (' moving ');

This.reset ();

}

Dynamic Set Translate3d parameter method

PageSlide.prototype.setX = function (el, X, unit) {

El && (el.style.webkitTransform = ' Translate3d (' + x + (unit | | ' px ') + ', 0,0) ';

};

PageSlide.prototype.setY = function (el, Y, unit) {

El && (el.style.webkitTransform = ' Translate3d (0, ' + y + (unit | | ' px ') + ', 0 ');

};

To set the current touch page Translate3d parameter to 0

PageSlide.prototype.setCurrent = function (el, i) {

El && (el.style.webkitTransform = ' Translate3d (0,0,0) ');

if (i) {

This.current = i;

this. $current = this. $el. Children[i];

}

}

Call the Go () method to go to the next or previous page

PageSlide.prototype.next = function () {

This.go (this.current + 1);

};

PageSlide.prototype.prev = function () {

This.go (this.current-1);

};

Reset method for initialization and reset of the current page

PageSlide.prototype.reset = function () {

var width = this.width;

var height = this.height;

var swipe = This.swipe;

var current = This.getcurrent ();

var prev = current.previouselementsibling;

var next = current.nextelementsibling;

This.setcurrent (current);

Prev && (this[' set ' + swipe] (prev,-(swipe = = = ' X ' width:height)));

Next && (this[' set ' + swipe] (next, swipe = = = ' X ' width:height));

}

Go to the next or previous page go method

PageSlide.prototype.go = function (i) {

var onfinish = this.options.onFinish;

var current = This.getcurrent ();

var total = this. $el. Childelementcount;

var target = this. $el. Children[i];

var d = i < this.current? -1:1;

if (i = = = This.current | | I < 0 | | I >= total) return;

if (OnFinish && (typeof onfinish = = = ' function ')) Onfinish.call (this, i);

Swipe to finish calling method

typeof This.options.tranSetionEnd = = = ' function ' && this.options.tranSetionEnd.call (this);

This.current = i;

this[' Set ' + this.swipe] (current,-d * (this.swipe = = = ' X ' this.width:this.height)); The problem lies

This.setcurrent (target, i);

This.finish (current, target);

};

Delete the current page when the slide is complete. Play tag and add the. Play flag for the next page

PageSlide.prototype.finish = function (Curr, target) {

This.flag = null;

SetTimeout (function () {

Curr && curr.classList.remove (' play ');

Target && Target.classList.add (' play ');

}, 3e2);

};

Direct access to any page method

/* Method of direct access to a page, because of the needs of personal research, wrote this method, to start from any page can still maintain a normal sliding experience, you need to direct the page in front of all the pages of the Translate3d parameters are set to (0,-height,0) */

PageSlide.prototype.direct = function (i) {

if (i&&typeof (i) = = = ' number ') {

This.go (i);

for (var j = 0; j< i; j + +) {

this[' Set ' + This.swipe] (this. $el. children[j], 1 * (this.swipe = = = ' X ' this.width:this.height));

};

}

else return;

};

Pass the reference

Document.addeventlistener (' Touchmove ', function (e) {

E.preventdefault ();

});

var pages = new Pageslide (Document.queryselector ('. Pages '), ' Y ', {

Transetionend:function () {

Console.log (this.current);

}

});

Case Demo:

Horizontal Sliding screen case :

The idea of horizontal sliding screen is similar to portrait, in this demo only need to change the parameters passed from "Y" to "X".

Pass the reference
Document.addeventlistener (' Touchmove ', function (e) {
E.preventdefault ();
});
var pages = new Pageslide (Document.queryselector ('. Pages '), ' X ', {
Transetionend:function () {
Console.log (this.current);
}
});

Case Demo:

H5 Case sharing: Mobile slide-screen Touch Event

Related Article

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.