Hammer. js + carousel principle to implement simple sliding screen function _ javascript skills

Source: Internet
Author: User
Tags bootstrap carousel
This article mainly introduces Hammer. js + carousel principles to implement concise slip screen function related information, need friends can refer to the recent task, do a very small h5 application, only 2 screens, you need to perform horizontal full-screen sliding switching and some simple animation effects. Previously, fullpage was used for this kind of thing. js and jquery have poor performance, so I want to do something simple by myself. Finally, I used zepto + hammer. js and carousel to solve this problem. The effect is good. When Gzip is not enabled on the entire page, the data size of all resource requests is about KB. This article summarizes the implementation ideas of this method.

Demo:


1. Key Points of implementation

1) sliding screens use the bootstrap carousel plug-in for reference, but it is not as complicated as it is. You just need to use its carousel Implementation ideas for reference;

2) the triggering of screen sliding is different from that of a PC. a pc is usually triggered through the click callback of an element. The hashchange event of the window can be used to process the page sliding, in this way, you only need to set the anchor through a hyperlink or change the location through js. hash triggers switching;

3) Considering that mobile has to support gesture operations, the hammer. js gesture library can be used, and the API is very easy to use;

4. You can use animate.css for animation effects, but you only need to copy the required code for animation effects instead of getting all its code into the code;

5) zepto is preferred for jquery;

6) The Sliding Screen Effect uses the transition animation. To respond to the callback after the animation ends, you can consider using the transition. js, which is also a tool provided by Bootstrap. However, it can only be used with jquery by default. You need to change it a little before using it with zepto.

These points are rough and will be detailed later.

2. html Structure

The html structure of an empty Sliding Screen page is as follows:

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 are initialized with absolute positioning and full screen layout. Each section. page represents a page and is not displayed by default. All pages are located in the same way. That is to say, if all pages are displayed, these pages overlap.

The html structure of the demo page is:

Next Page

1

Previous Page

2

Previous Page

3

The demo-related css will not be displayed. In this example, animatedis applied to animate.css. animate.css is an animation library, which is available on github.

3. Implementation of Sliding Screen Switching

Sliding Screen switching is implemented by controlling two pages to be sliding through js to add and delete these css classes defined below:

.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 indicates the currently displayed page. After page initialization, use the following js call to add. page-active to the first page:

Var $ activePage; // initialize the first page (function () {$ activePage = $ ('# page-1'); $ activePage. addClass ('page -- active ');})();

In this way, the first page is displayed by default. Slide the screen to the left to illustrate how these css works:

Step 1: locate the section on the next page, add the page -- next class, and locate it on the right of the current page to prepare for sliding screen;

Step 2: locate the section of the current page and add page -- active-left to it. Because this class changes the value of the translate3D attribute, the current page slides to the left;

At the same time in step 2, add page -- next-left to section on the next page. Because this class changes the value of the translate3D attribute, the next page slides to the left;

Step 3: after the current page and the next page are animated, find the current page and remove the page -- active and page -- active-left classes;

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

The gif image is described as follows:


The principle of sliding the screen to the right is similar:

Step 1: locate the section of the previous page, add the page -- prev class, and locate it on the left of the current page to prepare for the sliding screen;

Step 2: locate the section of the current page and add page -- active-right to it. Because this class changes the value of the translate3D attribute, the current page slides to the right;

In step 2, add page -- prev-right to the section of the previous page. Because this class changes the value of the translate3D attribute, the previous page slides to the right;

Step 3: after the current page and the previous page are animated, find the current page and remove the page -- active and page -- active-right types;

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

Based on the above implementation principles, the JS functions are encapsulated as follows:

var TRANSITION_DURATION = 400, 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 by default during page initialization, the latest current page is updated after each screen sliding, therefore, you only need to pass the ID of the target page to the slide function during the call. The above code may have doubts:

1) $ targetPage [0]. offsetWidth: This code is used to trigger the re-painting of the browser, because the target page is originally displayed: none. If the re-painting is not triggered, the animation effect will not be visible after the css class is added in the next step;

2) The functions of $. transitionEnd. end and emulateTransitionEnd are described in the next section.

4. Callback and simulation of the end of the css animation in the browser

Bootstrap provides a tool named transition. js, used to determine whether the browser supports css animation callback events, and manually triggers callback when the browser does not automatically trigger callback after the animation ends, previously, this tool can only be used with jquery. To use it in zepto, you must change it a little. The following is the changed code:

(function(){var transition = $.transitionEnd = {end: (function () {var el = document.createElement('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 false;})()};$.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 indicates the name of the animation end event supported by the browser. $. Fn. emulateTransitionEnd is a method that extends the Zepto prototype and passes in the transition time of an animation. After this time period expires, if the browser does not automatically trigger the callback event, called will always be false, setTimeout will cause the callback to be called, and then the callback will manually trigger the callback after the animation ends. Why do we need to simulate the animation end in this way, because even if the browser supports the callback of the animation end event, this event is not triggered sometimes, or cannot be triggered immediately after the animation ends, this affects the accuracy of callback. The input duration should be the same as the animation execution element and the transtion-duration set on css. Note that the yellow part is marked in the following code:

var TRANSITION_DURATION = 400 ;$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. hashchange event

On the PC side, sliding screens are triggered by adding click events to elements. On the mobile side, you can use the hashchange event of the window:

$(window).on('hashchange', function (e) {var hash = location.hash;if (!hash) hash = '#page-1';slide(hash.substring(1));});location.hash = '#page-1';

The hashchange event is triggered when the loaction. hash event is changed in the js Code or when a hyperlink such as the next page is clicked. Therefore, you only need to perform Sliding Screen switching in the callback of this event. In this way, the link elements of the previous and next pages do not need to be added with events.

6. Introduction to hammer. js

Hammer. js is a gesture library that supports common gesture operations. It is easy to use. After introducing its js, it supports gesture Sliding Screen in the following ways:

// Initialize 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 ('swiperror', function (e) {swipteTo ('prev', e) ;}); function swipteTo (slideType, e) {var $ targetPage = $ activePage [slideType] ('. page '); $ targetPage. length & (location. hash = '#' + $ targetPage. attr ('id '));}

When the entire container element is used as the stage of the sliding screen, listening to the swipeleft event indicates sliding to the left, the next page should be displayed, and listening to the swiperight event indicates sliding to the right, the next page is displayed.

7. Conclusion

The usage of animate.css is not described in detail. It is relatively simple. This is its github address: https://github.com/daneden/animate.css, which is a very useful animation library. This article records some recent work experiences. Sometimes some words cannot be completely clear about technical things, therefore, I have to do my best to give some questions a little more detail. If I am not correct or have any questions, I will check them carefully in the comment area, in addition, I am not very familiar with mobile terminals. You have better insights. Please share with us. Thank you for reading this article. The New Year is coming soon!

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.