Use the carousel principle and hammer. js to implement simple Sliding Screen functions.

Source: Internet
Author: User

Use the carousel principle and hammer. js to implement simple Sliding Screen functions.

Recently, I have a task for a very small h5 application with only 2 screens. I need to perform horizontal full screen sliding switching and some simple animation effects, previously, fullpage was used to do this. 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 (Code download ):

<Div id = "container" class = "container"> <section id = "page-1" class = "page -- 1"> </section> <section id =" page-2 "class =" page -- 2 "> </section> <section id =" page-3 "class =" 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 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:

<Div id = "container" class = "container"> <section id = "page-1" class = "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 -- 2"> <div class = "page _ jump"> <a href = "# page-1" title = ""> previous page </a> <a href = "# page-3" title = ""> next page </a> </div> <p class = "page _ num animated"> 2 </p> </section> <section id = "page-3" class = "page -- 3"> <div class = "page _ jump"> <a href = "# page-2" title = ""> previous page </a> </div> <p class = "page _ num animated "> 3 </p> </section> </div>

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.

Gif image description::

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';

Hashchange event, by changing loaction in js Code. it is triggered when you click a hyperlink such as <a href = "# page-2" title = ""> next </a>, therefore, you only need to perform screen sliding 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!

Download the source code of this Article

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.