Hammer.js+ Wheel-Seeding principle to realize simple slide screen function _javascript skill

Source: Internet
Author: User
Tags prepare prev visibility bootstrap carousel

I have a mission recently. Make a very small H5 application, only 2 screen, need to do horizontal full-screen sliding switch and some simple animation effect, before doing this thing with Fullpage.js and jquery, performance is not very good, so I want to do a simple thing to achieve. Finally, I used Zepto + hammer.js and carousel to solve the problem, the effect is good, the entire page does not open gzip when all resources requested data size of 200KB or so. This article summarizes the realization of this method.

Effect Demo:


1. Implementation Essentials

1) Slide screen for reference Bootstrap Carousel plug-in, but completely without it that complex, only need to learn from its carousel to realize the idea can;

2 The trigger of the sliding screen switch, unlike the PC, the PC is usually triggered by the click callback of the element, and the page of the slide screen can be handled by the Hashchange event of the window completely. So as long as the hyperlink set anchor point or through JS change Location.hash can trigger the switch;

3 in view of the mobile also need to support gesture operation, you can use hammer.js this gesture library, the API is very simple and easy-to-use;

4 animation effect can be used animate.css, but do not have all of its code into the code, only need to copy the animation effect of the relevant code;

5 instead of jquery, preferred zepto;

6 slide screen effect using transition animation, in order to be able to respond to the animation end of the callback, Consider using Transition.js, which is also a tool provided by bootstrap, but it can only be used with jquery by default, and a slight change to it can be used in conjunction with Zepto.

These points are relatively rough, the following content will be introduced in detail.

2. HTML structure

The HTML structure of the empty slide-screen page is this:

<div id= "container" class= "container" >
<section id= "page-1" class= "page page--1" >
</section >
<section id= "page-2" class= "page page--2" >
</section>
<section id= "page-3" class= " Page page--3 ">
</section>
</div>

Html

body {
height:100%;
-webkit-tap-highlight-color:transparent
}
. container,
. page {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
Overflow:hidden
}
. page {
Overflow:hidden;
Display:none;
-webkit-transition:-webkit-transform 4s ease;
Transition:transform 4s ease;
-webkit-backface-visibility:hidden;
Backface-visibility:hidden;
}

. Container and. Page initialization with absolute positioning, full screen layout. Each section.page represents a page and is not displayed by default, and all pages are positioned the same, meaning that if all the pages are displayed, the pages will overlap.

The HTML structure of the demo page is:

<div id= "container" class= "container" >
<section id= "page-1" class= "page page--1" >
<div class= "Page__jump" ><a href= "#page-2" title= "" > next page </a></div> <p class= "Page__num animated
" >1</p>
</section>
<section id= "page-2" class= "page page--2" >
<div class= "Page_ _jump "><a href=" #page-1 "title=" "> Prev </a><a href=" #page-3 "title=" "> Next </a></div>
<p class= "page__num animated" >2</p>
</section> <section id= "page-3" class= "
page Page--3 ">
<div class=" page__jump "><a href=" #page-2 "title=" "> previous page </a></div>
<p class= "Page__num animated" >3</p>
</section>
</div>

Demo-related CSS will not be shown. Which animated is the application of animate.css needs, ANIMATE.CSS is an animation library, GitHub on there.

3. The realization idea of sliding screen switch

Sliding screen switching is through JS Control 2 to slide the page to add and remove the following definition of this CSS class implementation:

. page.page--active,
. Page.page--prev,
. page.page--next {
display:block;
}
. Page.page--next,
. page.page--active.page--active-right {
-webkit-transform:translate3d (100%, 0, 0);
Transform:translate3d (100%, 0, 0);
}
. Page.page--prev,
. page.page--active.page--active-left {
-webkit-transform:translate3d ( -100%, 0, 0);
Transform:translate3d ( -100%, 0, 0);
Page.page--next.page--next-left,
. Page.page--prev.page--prev-right,
. page.page--active {
- Webkit-transform:translate3d (0, 0, 0);
Transform:translate3d (0, 0, 0);
}

. page--active represents the currently displayed page, after the page initialization, through the following JS call, to the first page plus. Page-active:

var $activePage;
Initializes the first page
(function () {
$activePage = $ (' #page-1 ');
$activePage. addclass (' page--active ');
}) ();

This allows the page to display the first page by default. To explain to Zoshi how these CSS works:

The first step is to find the section on the next page, add the Page--next class, position it to the right of the current page, and prepare for the slide screen;

The second step, find the section of the current page, add page--active-left to it, because this class changes the value of the Translate3d property, so the current page will slide to the left a screen;

In the second step, add Page--next-left to the section of the next page, because this class changes the value of the Translate3d property, so the next page will slide to the left one screen;

The third step, after the current page with the next slide animation end, find the original current page, remove page--active and Page--active-left class;

In the third step, locate the next page, remove the Page--next and Page--next-left classes, and add the page--active.

The GIF diagram illustrates the following:


The right sliding screen principle is similar:

The first step is to find the section on the previous page, add the Page--prev class, position it to the left of the current page, and prepare for the slide screen;

The second step, find the section of the current page, add page--active-right to it, because this class changes the value of the Translate3d property, so the current page will slide to the right one screen;

In the second step, add Page--prev-right to the section on the previous page, because this class changes the value of the Translate3d property, so the previous page will slide to the right one screen;

The third step, after the current page with a slide screen animation end, find the original current page, remove page--active and Page--active-right class;

In the third step, locate the previous page, remove the Page--prev and Page--prev-right classes, and add the page--active.

The

synthesizes the above implementation principle, encapsulates the JS function as follows:

var transition_duration = =, sliding = false;
function Getslidetype ($targetPage) {var Activepageid = $activePage. attr (' id '), Targetpageid = $targetPage. attr (' id '); Return Activepageid < Targetpageid? ' Next ': Activepageid = = Targetpageid?
': ' prev '; function Slide (Targetpageid) {var $targetPage = $ (' # ' + Targetpageid); if (! $targetPage. Length | | sliding) return; var Slidetype = Getslidetype ($targetPage), direction = Slidetype = = ' Next '?
' Left ': ' Right ';
if (Slidetype = = ") return;
Sliding = true;
$targetPage. addclass (' page--' + slidetype);
$targetPage [0].offsetwidth;
$activePage. addclass (' page--active-' + direction);
$targetPage. addclass (' page--' + slidetype + '-' + direction);  $activePage. One ($.transitionend.end, function () {$targetPage. removeclass ([' page--' + slidetype, ' page--' + Slidetype +
'-' + direction].join (') '). addclass (' page--active ');
$activePage. Removeclass ([' page--active ', ' page--active-' + direction].join ("));
$activePage = $targetPage; Sliding = fAlse;
}). Emulatetransitionend (transition_duration); }

Because $activepage is specified as the first page when the page is initialized, it is updated to the current page at the end of each slide, so it is only possible to pass the ID of the target page to the slide function when it is invoked. The above code may be in doubt:

1 $targetPage [0].offsetwidth role, this code is used to trigger the browser redraw, because the target page is originally display:none, if not trigger redraw, the next step to add CSS class will not see the animation effect;

2) The role of $.transitionend.end and Emulatetransitionend, as explained in the next section.

4. Browser CSS animation end of the callback and simulation

Bootstrap provides a tool to Transition.js, used to determine whether the browser supports CSS animation callback events, and in the browser does not automatically trigger the callback after the animation of the special case to manually trigger the callback, the original tool can only be used in conjunction with jquery, in order to use in the Zepto, you have to change a little bit, the following is to The code after the change:

 (function () {var transition = $.transitionend = {end: (function () {var el = document.cr Eateelement (' Transitionend '), Transendeventnames = {webkittransition: ' Webkittransitionend ', MozTransition: '
Transitionend ', otransition: ' Otransitionend otransitionend ', Transition: ' Transitionend '}; for (var name in transendeventnames) {if (El.style[name]!== undefined) {return transendeventnames[name];} return FAL
Se
})()
}; $.fn.emulatetransitionend = function (duration) {var called = false, _this = this, callback = function () {if (!called)
$ (_this). Trigger (Transition.end);
};
$ (this). One (Transition.end, function () {called = true;});
SetTimeout (callback, duration);
return this;
}; 
})();

$.transitionend.end represents the name of the animated end event supported by the current browser. $.fn.emulatetransitionend is a way to extend the Zepto prototype, passing in an animation transition time, when the time period is over, if the browser does not automatically trigger callback events, called is always false,settimeout will cause callback to be Call, and then the callback internally triggers a callback that ends the animation manually. Why this is the way to simulate the end of an animation, because the browser even supports the animation end of the event callback, but sometimes does not trigger the event, or at the end of the animation can not immediately trigger, affecting the accuracy of the callback. The incoming duration should be the same as the element that executes the animation, set on the CSS transtion-duration, note the following code the yellow part of the bid:

var transition_duration = n;
$activePage
. One ($.transitionend.end, function () {
$targetPage. removeclass ([' page--' + slidetype, ' page--' + Slidetype + '-' + direction].join (')). addclass (' page--active ');
$activePage. Removeclass ([' page--active ', ' page--active-' + direction].join ("));
$activePage = $targetPage;
Sliding = false;
})
. Emulatetransitionend (transition_duration); 
page {
Overflow:hidden;
Display:none;
-webkit-transition:-webkit-transform 4s ease;
Transition:transform 4s ease;
-webkit-backface-visibility:hidden;
Backface-visibility:hidden;
}

5. The Hashchange incident

The PC-side slide screen is triggered by adding a click event to the element, and the mobile end can take advantage of the window's Hashchange event:

$ (window). On (' Hashchange ', function (e) {
var hash = Location.hash;
if (!hash) hash = ' #page-1 ';
Slide (hash.substring (1));
};
Location.hash = ' #page-1 ';

Hashchange event, in the JS code by changing Loaction.hash or click <a href= "#page-2" title= "" > next page </a> such hyperlinks, will be triggered, So as long as the callback in this event to do a sliding screen switch. This way, the link elements for the previous and next pages are not added to the event.

6. Introduction to Hammer.js Use

Hammer.js is a gesture library, support commonly used gesture operation, using simple, the introduction of its JS, the following way to support the gesture slide screen:

Initialization gesture Sliding
var container = document.getElementById (' container '),
mc = new Hammer.manager (container),
swipe = new Hammer.swipe ();
Mc.add (swipe);
Mc.on (' Swipeleft ', function (e) {
swipteto (' Next ', e);
});
Mc.on (' Swiperight ', function (e) {
swipteto (' prev ', e);
});
function Swipteto (Slidetype, E) {
var $targetPage = $activePage [Slidetype] ('. Page ');
$targetPage. Length && (location.hash = ' # ' + $targetPage. attr (' id '));

The whole container element as the stage of the slide screen, monitor the Swipeleft event, which means that the left slide, the page should display the next page; If you hear the Swiperight event, it means that the page should display the next page.

7. Concluding remarks

The use of ANIMATE.CSS is not introduced in detail, relatively simple, this is its GitHub address: Https://github.com/daneden/animate.css, is a very useful animation library. This article has recorded a little bit of recent work experience, technical things, sometimes some words can not be completely clear, so I can only do their best to put some of the problems a little more detailed, said the wrong and problematic although in the comments area with me, I will carefully view, In addition to my own on the mobile end of this piece is not deep, you have a better view, welcome to share with us. Thank you for reading, immediately on the new Year, Wish you monkey!

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.