swipe.js 20 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
/**
 * @package plugin/swipe.js
 * @author:wzx (zhixiang.wang@yoho.cn)
 * @date:2014-03-03
 */
define('plugins/swipe', function(require, exports) {
    var $ = require("jquery");

    function Swipe(container, options) {

        "use strict";

        // utilities
        var noop = function() {}; // simple no operation function
        var offloadFn = function(fn) {
            setTimeout(fn || noop, 0)
        }; // offload a functions execution

        // 检测浏览器
        var browser = {
            addEventListener: !!window.addEventListener,
            touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
            transitions: (function(temp) {
                var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
                for (var i in props)
                    if (temp.style[props[i]] !== undefined) return true;
                return false;
            })(document.createElement('div'))
        };

        // quit if no root element
        if (!container) return;
        var element = container.children[0];
        var slides, slidePos, width, length;
        options = options || {};
        var index = parseInt(options.startSlide, 10) || 0;
        var speed = options.speed || 300;
        options.continuous = options.continuous !== undefined ? options.continuous : true;
        options.gif = false;

        function setup() {

            // cache slides
            slides = element.children;
            length = slides.length;

            // set continuous to false if only one slide
            if (slides.length < 2) options.continuous = false;

            //special case if two slides
            if (browser.transitions && options.continuous && slides.length < 3) {
                element.appendChild(slides[0].cloneNode(true));
                element.appendChild(element.children[1].cloneNode(true));
                slides = element.children;
            }

            // create an array to store current positions of each slide
            slidePos = new Array(slides.length);

            // determine width of each slide
            width = slides[0].getBoundingClientRect().width || slides[0].offsetWidth;

            element.style.width = (slides.length * width) + 'px';

            // stack elements
            var pos = slides.length;
            while (pos--) {

                var slide = slides[pos];

                slide.style.width = width + 'px';
                slide.setAttribute('data-index', pos);

                if (browser.transitions) {
                    slide.style.left = (pos * -width) + 'px';
                    move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
                }

            }

            // reposition elements before and after index
            if (options.continuous && browser.transitions) {
                move(circle(index - 1), -width, 0);
                move(circle(index + 1), width, 0);
            }

            if (!browser.transitions) element.style.left = (index * -width) + 'px';

            container.style.visibility = 'visible';

        }

        function prev() {

            if (options.gif) {
                (index == 0) && (slides[index + 1].style.visibility = 'hidden');
                if (index > 0) {
                    slides[index - 1].style.visibility = 'visible';
                    slides[index + 1].style.visibility = 'hidden';
                }
            }

            if (options.continuous) slide(index - 1);
            else if (index) slide(index - 1);

        }

        function next() {

            if (options.gif) {
                (index == slides.length - 1) && (slides[index + 1].style.visibility = 'hidden');
                if (index < slides.length - 1) {
                    slides[index - 1].style.visibility = 'visible';
                    slides[index + 1].style.visibility = 'hidden';
                }
            }

            if (options.continuous) slide(index + 1);
            else if (index < slides.length - 1) slide(index + 1);

        }

        function circle(index) {

            // a simple positive modulo using slides.length
            return (slides.length + (index % slides.length)) % slides.length;

        }

        function slide(to, slideSpeed) {

            // do nothing if already on requested slide
            if (index == to) return;

            if (browser.transitions) {

                var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward

                // get the actual position of the slide
                if (options.continuous) {
                    var natural_direction = direction;
                    direction = -slidePos[circle(to)] / width;

                    // if going forward but to < index, use to = slides.length + to
                    // if going backward but to > index, use to = -slides.length + to
                    if (direction !== natural_direction) to = -direction * slides.length + to;

                }

                var diff = Math.abs(index - to) - 1;

                // move all the slides between index and to in the right direction
                while (diff--) move(circle((to > index ? to : index) - diff - 1), width * direction, 0);

                to = circle(to);

                move(index, width * direction, slideSpeed || speed);
                move(to, 0, slideSpeed || speed);

                if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place

            } else {

                to = circle(to);
                animate(index * -width, to * -width, slideSpeed || speed);
                //no fallback for a circular continuous if the browser does not accept transitions
            }

            index = to;
            offloadFn(options.callback && options.callback(index, slides[index]));
        }

        function move(index, dist, speed) {

            translate(index, dist, speed);
            slidePos[index] = dist;

        }

        function translate(index, dist, speed) {

            var slide = slides[index];
            var style = slide && slide.style;

            if (!style) return;

            style.webkitTransitionDuration =
                style.MozTransitionDuration =
                style.msTransitionDuration =
                style.OTransitionDuration =
                style.transitionDuration = speed + 'ms';

            style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
            style.msTransform =
                style.MozTransform =
                style.OTransform = 'translateX(' + dist + 'px)';

        }

        function animate(from, to, speed) {

            // if not an animation, just reposition
            if (!speed) {

                element.style.left = to + 'px';
                return;

            }

            var start = +new Date;

            var timer = setInterval(function() {

                var timeElap = +new Date - start;

                if (timeElap > speed) {

                    element.style.left = to + 'px';

                    if (delay) begin();

                    options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

                    clearInterval(timer);
                    return;

                }

                element.style.left = (((to - from) * (Math.floor((timeElap / speed) * 100) / 100)) + from) + 'px';

            }, 4);

        }

        // setup auto slideshow
        var delay = options.auto || 0;
        var interval;

        function begin() {

            interval = setTimeout(next, delay);

        }

        function stop() {

            if (browser.touch) delay = 0;
            clearTimeout(interval);

        }


        // setup initial vars
        var start = {};
        var delta = {};
        var isScrolling;

        // setup event capturing
        var events = {

            handleEvent: function(event) {

                switch (event.type) {
                    case 'touchstart':
                        this.start(event);
                        break;
                    case 'touchmove':
                        this.move(event);
                        break;
                    case 'touchend':
                        offloadFn(this.end(event));
                        break;
                    case 'webkitTransitionEnd':
                    case 'msTransitionEnd':
                    case 'oTransitionEnd':
                    case 'otransitionend':
                    case 'transitionend':
                        offloadFn(this.transitionEnd(event));
                        break;
                    case 'resize':
                        offloadFn(setup);
                        break;
                }

                if (options.stopPropagation) event.stopPropagation();

            },
            start: function(event) {

                var touches = event.touches[0];

                // measure start values
                start = {

                    // get initial touch coords
                    x: touches.pageX,
                    y: touches.pageY,

                    // store time to determine touch duration
                    time: +new Date

                };

                // used for testing first move event
                isScrolling = undefined;

                // reset delta and end measurements
                delta = {};

                // attach touchmove and touchend listeners
                element.addEventListener('touchmove', this, false);
                element.addEventListener('touchend', this, false);

            },
            move: function(event) {

                // ensure swiping with one touch and not pinching
                if (event.touches.length > 1 || event.scale && event.scale !== 1) return

                if (options.disableScroll) event.preventDefault();

                var touches = event.touches[0];

                // measure change in x and y
                delta = {
                    x: touches.pageX - start.x,
                    y: touches.pageY - start.y
                }

                // determine if scrolling test has run - one time test
                if (typeof isScrolling == 'undefined') {
                    isScrolling = !!(isScrolling || Math.abs(delta.x) < Math.abs(delta.y));
                }

                // if user is not trying to scroll vertically
                if (!isScrolling) {

                    // prevent native scrolling
                    event.preventDefault();

                    // stop slideshow
                    stop();

                    // increase resistance if first or last slide
                    if (options.continuous) { // we don't add resistance at the end

                        translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);
                        translate(index, delta.x + slidePos[index], 0);
                        translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);

                    } else {

                        delta.x =
                            delta.x /
                            ((!index && delta.x > 0 // if first slide and sliding left
                                    || index == slides.length - 1 // or if last slide and sliding right
                                    && delta.x < 0 // and if sliding at all
                                ) ?
                                (Math.abs(delta.x) / width + 1) // determine resistance level
                                : 1); // no resistance if false

                        // translate 1:1
                        translate(index - 1, delta.x + slidePos[index - 1], 0);
                        translate(index, delta.x + slidePos[index], 0);
                        translate(index + 1, delta.x + slidePos[index + 1], 0);
                    }

                }

            },
            end: function(event) {

                // measure duration
                var duration = +new Date - start.time;

                // determine if slide attempt triggers next/prev slide
                var isValidSlide =
                    Number(duration) < 250 // if slide duration is less than 250ms
                    && Math.abs(delta.x) > 20 // and if slide amt is greater than 20px
                    || Math.abs(delta.x) > width / 2; // or if slide amt is greater than half the width

                // determine if slide attempt is past start and end
                var isPastBounds = !index && delta.x > 0 // if first slide and slide amt is greater than 0
                    || index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0

                if (options.continuous) isPastBounds = false;

                // determine direction of swipe (true:right, false:left)
                var direction = delta.x < 0;

                // if not scrolling vertically
                if (!isScrolling) {

                    if (isValidSlide && !isPastBounds) {

                        if (direction) {

                            if (options.continuous) { // we need to get the next in this direction in place

                                move(circle(index - 1), -width, 0);
                                move(circle(index + 2), width, 0);

                            } else {
                                move(index - 1, -width, 0);
                            }

                            move(index, slidePos[index] - width, speed);
                            move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);
                            index = circle(index + 1);

                        } else {
                            if (options.continuous) { // we need to get the next in this direction in place

                                move(circle(index + 1), width, 0);
                                move(circle(index - 2), -width, 0);

                            } else {
                                move(index + 1, width, 0);
                            }

                            move(index, slidePos[index] + width, speed);
                            move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);
                            index = circle(index - 1);

                        }

                        options.callback && options.callback(index, slides[index]);

                    } else {

                        if (options.continuous) {

                            move(circle(index - 1), -width, speed);
                            move(index, 0, speed);
                            move(circle(index + 1), width, speed);

                        } else {

                            move(index - 1, -width, speed);
                            move(index, 0, speed);
                            move(index + 1, width, speed);
                        }

                    }

                }

                // kill touchmove and touchend event listeners until touchstart called again
                element.removeEventListener('touchmove', events, false)
                element.removeEventListener('touchend', events, false)

            },
            transitionEnd: function(event) {

                if (parseInt(event.target.getAttribute('data-index'), 10) == index) {

                    if (delay) begin();

                    options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

                }
            }

        }

        // trigger setup
        setup();

        // start auto slideshow if applicable
        if (delay) begin();


        // add event listeners
        if (browser.addEventListener) {

            // set touchstart event on element
            if (browser.touch) element.addEventListener('touchstart', events, false);

            if (browser.transitions) {
                element.addEventListener('webkitTransitionEnd', events, false);
                element.addEventListener('msTransitionEnd', events, false);
                element.addEventListener('oTransitionEnd', events, false);
                element.addEventListener('otransitionend', events, false);
                element.addEventListener('transitionend', events, false);
            }

            // set resize event on window
            window.addEventListener('resize', events, false);

        } else {

            window.onresize = function() {
                setup()
            }; // to play nice with old IE

        }

        // expose the Swipe API
        return {
            setup: function() {

                setup();

            },
            slide: function(to, speed) {

                // cancel slideshow
                stop();

                slide(to, speed);

            },
            prev: function() {

                // cancel slideshow
                stop();

                prev();

            },
            next: function() {

                // cancel slideshow
                stop();

                next();

            },
            stop: function() {

                // cancel slideshow
                stop();

            },
            getPos: function() {

                // return current index position
                return index;

            },
            getNumSlides: function() {

                // return total number of slides
                return length;
            },
            kill: function() {

                // cancel slideshow
                stop();

                // reset element
                element.style.width = '';
                element.style.left = '';

                // reset slides
                var pos = slides.length;
                while (pos--) {

                    var slide = slides[pos];
                    slide.style.width = '';
                    slide.style.left = '';

                    if (browser.transitions) translate(pos, 0, 0);

                }

                // removed event listeners
                if (browser.addEventListener) {

                    // remove current event listeners
                    element.removeEventListener('touchstart', events, false);
                    element.removeEventListener('webkitTransitionEnd', events, false);
                    element.removeEventListener('msTransitionEnd', events, false);
                    element.removeEventListener('oTransitionEnd', events, false);
                    element.removeEventListener('otransitionend', events, false);
                    element.removeEventListener('transitionend', events, false);
                    window.removeEventListener('resize', events, false);

                } else {
                    window.onresize = null;
                }

            }
        }
    }

    exports.init = function(options) {
        var opt = {
            slideBox: '#feed-slide',
            prev: '.sliderLeft',
            next: '.sliderRight',
            pagination: '.slideControl a',
            activeClass: 'on',
            auto: 3000,
            isControls: true,
            isPagination: true,
            gif: false,
            continuous: false
        }

        opt = $.extend(opt, options);

        var mySwipe = Swipe($(opt.slideBox)[0], {
            startSlide: 0,
            speed: 400,
            auto: opt.auto,
            continuous: opt.continuous,
            disableScroll: false,
            stopPropagation: false,
            gif: opt.gif,
            /*callback: function(index) {
                //当出现两个变成四个时,bug
                if (index >= $(opt.pagination).size()) {
                    index = index - $(opt.pagination).size();
                }
                $(opt.pagination).removeClass(opt.activeClass).eq(index).addClass(opt.activeClass);
            }*/
            callback: opt.callback
        });

        if (opt.isControls) {
            $(opt.prev).click(function() {
                mySwipe.prev();
            });

            $(opt.next).click(function() {
                mySwipe.next();
            });
        }

        if (opt.isPagination) {
            $(opt.pagination).click(function() {
                mySwipe.slide($(this).index());
            });
        }
        return mySwipe;
    }
});