JavaScript核心-6. 移动端网页特效

一、触屏事件

1. 触屏事件

移动端浏览器兼容性较好,我们不需要考虑以前 JS 的兼容性问题,可以放心的使用原生 JS 书写效果,但是移动端也有自己独特的地方。比如触屏事件 touch(也称触摸事件),Android 和 IOS 都有。

touch 对象代表一个触摸点。触摸点可能是一根手指,也可能是一根触摸笔。触屏事件可响应用户手指(或触控笔)对屏幕或者触控板操作。

常见的触屏事件如下:
在这里插入图片描述

// 1. 获取元素
        // 2. 手指触摸DOM元素事件
        var div = document.querySelector('div');
        div.addEventListener('touchstart', function() {
            console.log('我摸了你');
        });
        // 3. 手指在DOM元素身上移动事件
        div.addEventListener('touchmove', function() {
            console.log('继续摸');
        });
        // 4. 手指离开DOM元素事件
        div.addEventListener('touchend', function() {
            console.log('我走了');
        });

2. 触摸事件对象(TouchEvent)

TouchEvent 是一类描述手指在触摸平面(触摸屏、触摸板等)的状态变化的事件。这类事件用于描述一个或多个触点,使开发者可以检测触点的移动,触点的增加和减少,等等

touchstart、touchmove、touchend 三个事件都会各自有事件对象。

触摸事件对象重点我们看三个常见对象列表:
在这里插入图片描述
因为平时我们都是给元素注册触摸事件,所以 重点记住targetTocuhes

// 触摸事件对象
        // 1. 获取元素
        // 2. 手指触摸DOM元素事件
        var div = document.querySelector('div');
        div.addEventListener('touchstart', function(e) {
            // console.log(e);
            // touches 正在触摸屏幕的所有手指的列表 
            // targetTouches 正在触摸当前DOM元素的手指列表
            // 如果侦听的是一个DOM元素,他们两个是一样的
            // changedTouches 手指状态发生了改变的列表 从无到有 或者 从有到无
            // 因为我们一般都是触摸元素 所以最经常使用的是 targetTouches
            // targetTouches[0] 就可以得到正在触摸dom元素的第一个手指的相关信息比如 手指的坐标等等
            console.log(e.targetTouches[0]);
        });
        // 3. 手指在DOM元素身上移动事件
        div.addEventListener('touchmove', function() {
        });
        // 4. 手指离开DOM元素事件
        div.addEventListener('touchend', function(e) {
            // console.log(e);
            // 当我们手指离开屏幕的时候,就没有了 touches 和 targetTouches 列表
            // 但是会有 changedTouches
        });

3. 移动端拖动元素

  1. touchstart、touchmove、touchend 可以实现拖动元素
  2. 但是拖动元素需要当前手指的坐标值 我们可以使用 targetTouches[0] 里面的pageX 和 pageY
  3. 移动端拖动的原理: 手指移动中,计算出手指移动的距离。然后用盒子原来的位置 + 手指移动的距离
  4. 手指移动的距离: 手指滑动中的位置 减去 手指刚开始触摸的位置

拖动元素三步曲:
(1) 触摸元素 touchstart: 获取手指初始坐标,同时获得盒子原来的位置
(2) 移动手指 touchmove: 计算手指的滑动距离,并且移动盒子
(3) 离开手指 touchend:

注意: 手指移动也会触发滚动屏幕所以这里要阻止默认的屏幕滚动 e.preventDefault();

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        // (1) 触摸元素 touchstart:  获取手指初始坐标,同时获得盒子原来的位置
        // (2) 移动手指 touchmove:  计算手指的滑动距离,并且移动盒子
        // (3) 离开手指 touchend:
        var div = document.querySelector('div');
        var startX = 0; //获取手指初始坐标
        var startY = 0;
        var x = 0; //获得盒子原来的位置
        var y = 0;
        div.addEventListener('touchstart', function(e) {
            //  获取手指初始坐标
            startX = e.targetTouches[0].pageX;
            startY = e.targetTouches[0].pageY;
            x = this.offsetLeft;
            y = this.offsetTop;
        });

        div.addEventListener('touchmove', function(e) {
            //  计算手指的移动距离: 手指移动之后的坐标减去手指初始的坐标
            var moveX = e.targetTouches[0].pageX - startX;
            var moveY = e.targetTouches[0].pageY - startY;
            // 移动我们的盒子 盒子原来的位置 + 手指移动的距离
            this.style.left = x + moveX + 'px';
            this.style.top = y + moveY + 'px';
            e.preventDefault(); // 阻止屏幕滚动的默认行为
        });
    </script>
</body>

</html>

效果图
在这里插入图片描述

二、移动端常见特效

1. classList 属性

classList属性是HTML5新增的一个属性,返回元素的类名。但是ie10以上版本支持。
该属性用于在元素中添加,移除及切换 CSS 类。有以下方法

添加类:
element.classList.add(’类名’);

focus.classList.add(‘current’);

移除类:
element.classList.remove(’类名’);

focus.classList.remove(‘current’);

切换类:
element.classList.toggle(’类名’);

focus.classList.toggle(‘current’);

注意以上方法里面,所有类名都不带点

.bg {
	background-color: black;
	}
<body>
    <div class="one two"></div>
    <button> 开关灯</button>
    <script>
        // classList 返回元素的类名
        var div = document.querySelector('div');
        // console.log(div.classList[1]);
        // 1. 添加类名  是在后面追加类名不会覆盖以前的类名 注意前面不需要加.
        div.classList.add('three');
        // 2. 删除类名
        div.classList.remove('one');
        // 3. 切换类
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            document.body.classList.toggle('bg');
        })
    </script>
</body>

2. 案例:移动端轮播图

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
index.html 代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css/carousel.css">
    <title></title>
    <script src="js/carousel.js"></script>
</head>

<body>
    <!-- 焦点图模块 -->
    <div class="focus">
        <ul>
            <li><img src="upload/focus3.jpg" alt=""></li>
            <li><img src="upload/focus1.jpg" alt=""></li>
            <li><img src="upload/focus2.jpg" alt=""></li>
            <li><img src="upload/focus3.jpg" alt=""></li>
            <li><img src="upload/focus1.jpg" alt=""></li>
        </ul>
        <!-- 小圆点 -->
        <ol>
            <li class="current"></li>
            <li></li>
            <li></li>
        </ol>
    </div>
</body>

</html>

carousel.css 代码如下:

body {
    max-width: 540px;
    min-width: 320px;
    margin: 0 auto;
    font: normal 14px/1.5 Tahoma, "Lucida Grande", Verdana, "Microsoft Yahei", STXihei, hei;
    color: #000;
    background: #f2f2f2;
    overflow-x: hidden;
    -webkit-tap-highlight-color: transparent;
}

ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

a {
    text-decoration: none;
    color: #222;
}

div {
    box-sizing: border-box;
}

/* focus */

.focus {
    position: relative;
    padding-top: 44px;
    overflow: hidden;
}

.focus img {
    width: 100%;
}

.focus ul {
    overflow: hidden;
    width: 500%;
    margin-left: -100%;
}

.focus ul li {
    float: left;
    width: 20%;
}

.focus ol {
    position: absolute;
    bottom: 5px;
    right: 5px;
    margin: 0;
}

.focus ol li {
    display: inline-block;
    width: 5px;
    height: 5px;
    background-color: #fff;
    list-style: none;
    border-radius: 2px;
    transition: all .3s;
}

.focus ol li.current {
    width: 15px;
}

carousel.js 代码如下:

window.addEventListener('load', function() {
    // alert(1);
    // 1. 获取元素 
    var focus = document.querySelector('.focus');
    var ul = focus.children[0];
    // 获得focus 的宽度
    var w = focus.offsetWidth;
    var ol = focus.children[1];
    // 2. 利用定时器自动轮播图图片
    var index = 0;
    var timer = setInterval(function() {
        index++;
        var translatex = -index * w;
        ul.style.transition = 'all .3s';
        ul.style.transform = 'translateX(' + translatex + 'px)';
    }, 2000);
    // 等着我们过渡完成之后,再去判断 监听过渡完成的事件 transitionend 
    ul.addEventListener('transitionend', function() {
        // 无缝滚动
        if (index >= 3) {
            index = 0;
            // console.log(index);
            // 去掉过渡效果 这样让我们的ul 快速的跳到目标位置
            ul.style.transition = 'none';
            // 利用最新的索引号乘以宽度 去滚动图片
            var translatex = -index * w;
            ul.style.transform = 'translateX(' + translatex + 'px)';
        } else if (index < 0) {
            index = 2;
            ul.style.transition = 'none';
            // 利用最新的索引号乘以宽度 去滚动图片
            var translatex = -index * w;
            ul.style.transform = 'translateX(' + translatex + 'px)';
        }
        // 3. 小圆点跟随变化
        // 把ol里面li带有current类名的选出来去掉类名 remove
        ol.querySelector('.current').classList.remove('current');
        // 让当前索引号 的小li 加上 current   add
        ol.children[index].classList.add('current');
    });

    // 4. 手指滑动轮播图 
    // 触摸元素 touchstart: 获取手指初始坐标
    var startX = 0;
    var moveX = 0; // 后面我们会使用这个移动距离所以要定义一个全局变量
    var flag = false;
    ul.addEventListener('touchstart', function(e) {
        startX = e.targetTouches[0].pageX;
        // 手指触摸的时候就停止定时器
        clearInterval(timer);
    });
    // 移动手指 touchmove: 计算手指的滑动距离, 并且移动盒子
    ul.addEventListener('touchmove', function(e) {
        // 计算移动距离
        moveX = e.targetTouches[0].pageX - startX;
        // 移动盒子:  盒子原来的位置 + 手指移动的距离 
        var translatex = -index * w + moveX;
        // 手指拖动的时候,不需要动画效果所以要取消过渡效果
        ul.style.transition = 'none';
        ul.style.transform = 'translateX(' + translatex + 'px)';
        flag = true; // 如果用户手指移动过我们再去判断否则不做判断效果
        e.preventDefault(); // 阻止滚动屏幕的行为
    });
    // 手指离开 根据移动距离去判断是回弹还是播放上一张下一张
    ul.addEventListener('touchend', function(e) {
        if (flag) {
            // (1) 如果移动距离大于50像素我们就播放上一张或者下一张
            if (Math.abs(moveX) > 50) {
                // 如果是右滑就是 播放上一张 moveX 是正值
                if (moveX > 0) {
                    index--;
                } else {
                    // 如果是左滑就是 播放下一张 moveX 是负值
                    index++;
                }
                var translatex = -index * w;
                ul.style.transition = 'all .3s';
                ul.style.transform = 'translateX(' + translatex + 'px)';
            } else {
                // (2) 如果移动距离小于50像素我们就回弹
                var translatex = -index * w;
                ul.style.transition = 'all .1s';
                ul.style.transform = 'translateX(' + translatex + 'px)';
            }
        }
        // 手指离开的时候就重新开启定时器
        clearInterval(timer);
        timer = setInterval(function() {
            index++;
            var translatex = -index * w;
            ul.style.transition = 'all .3s';
            ul.style.transform = 'translateX(' + translatex + 'px)';
        }, 2000);
    });
})

效果图
在这里插入图片描述

3. 案例:返回顶部

在这里插入图片描述
在这里插入图片描述
index.html 代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <!-- <link rel="stylesheet" href="css/normalize.css"> -->
    <link rel="stylesheet" href="css/goback.css">
    <title></title>
    <script src="js/carousel.js"></script>
</head>

<body>
    <!-- 返回顶部模块 -->
    <div class="goBack"></div>
	<div class="qita"></div>
    <!-- 主导航栏 -->
    <nav>
    </nav>
    
</body>

</html>

goback.css 代码如下:

body {
    max-width: 540px;
    min-width: 320px;
    margin: 0 auto;
    font: normal 14px/1.5 Tahoma, "Lucida Grande", Verdana, "Microsoft Yahei", STXihei, hei;
    color: #000;
    background: #f2f2f2;
    overflow-x: hidden;
    -webkit-tap-highlight-color: transparent;
}

/* goBack */

.goBack {
    display: none;
    position: fixed;
    bottom: 50px;
    right: 20px;
    width: 38px;
    height: 38px;
    background: url(../images/back.png) no-repeat;
    background-size: 38px 38px;
}

/*其他*/
.qita {
	height: 100px;
	background-color: red;
}
/* nav */

nav {
	height: 600px;
    background-color: coral;
}

goback.js 代码如下:

window.addEventListener('load', function() {
    // 返回顶部模块制作
    var goBack = document.querySelector('.goBack');
    var nav = document.querySelector('nav');
    window.addEventListener('scroll', function() {
        if (window.pageYOffset >= nav.offsetTop) {
            goBack.style.display = 'block';
        } else {
            goBack.style.display = 'none';
        }
    });
    goBack.addEventListener('click', function() {
        window.scroll(0, 0);
    })
})

效果图
在这里插入图片描述

4. click 延时解决方案

移动端 click 事件会有 300ms 的延时,原因是移动端屏幕双击会缩放(double tap to zoom) 页面。

解决方案:

  1. 禁用缩放。 浏览器禁用默认的双击缩放行为并且去掉 300ms 的点击延迟。

    <meta name="viewport" content="user-scalable=no">

  2. 利用touch事件自己封装这个事件解决 300ms 延迟。

原理就是:

  1. 当我们手指触摸屏幕,记录当前触摸时间
  2. 当我们手指离开屏幕, 用离开的时间减去触摸的时间
  3. 如果时间小于150ms,并且没有滑动过屏幕, 那么我们就定义为点击
//封装tap,解决click 300ms 延时
function tap (obj, callback) {
        var isMove = false;
        var startTime = 0; // 记录触摸时候的时间变量
        obj.addEventListener('touchstart', function (e) {
            startTime = Date.now(); // 记录触摸时间
        });
        obj.addEventListener('touchmove', function (e) {
            isMove = true;  // 看看是否有滑动,有滑动算拖拽,不算点击
        });
        obj.addEventListener('touchend', function (e) {
            if (!isMove && (Date.now() - startTime) < 150) {  // 如果手指触摸和离开时间小于150ms 算点击
                callback && callback(); // 执行回调函数
            }
            isMove = false;  //  取反 重置
            startTime = 0;
        });
}
//调用  
  tap(div, function(){   // 执行代码  });

三、移动端常用开发插件

1. 插件

移动端要求的是快速开发,所以我们经常会借助于一些插件来帮我完成操作

JS 插件是 js 文件,它遵循一定规范编写,方便程序展示效果,拥有特定功能且方便调用。如轮播图和瀑布流插件。

特点:它一般是为了解决某个问题而专门存在,其功能单一,并且比较小。
我们以前写的animate.js 也算一个最简单的插件

2. fastclick 插件

fastclick 插件解决 300ms 延迟。 使用延时
GitHub官网地址: https://github.com/ftlabs/fastclick

fastclick.js 代码如下:

;
(function() {
    'use strict';
    /**
     * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
     *
     * @codingstandard ftlabs-jsv2
     * @copyright The Financial Times Limited [All Rights Reserved]
     * @license MIT License (see LICENSE.txt)
     */

    /*jslint browser:true, node:true*/
    /*global define, Event, Node*/

    /**
     * Instantiate fast-clicking listeners on the specified layer.
     *
     * @constructor
     * @param {Element} layer The layer to listen on
     * @param {Object} [options={}] The options to override the defaults
     */
    function FastClick(layer, options) {
        var oldOnClick;

        options = options || {};
        /**
         * Whether a click is currently being tracked.
         *
         * @type boolean
         */
        this.trackingClick = false;
        /**
         * Timestamp for when click tracking started.
         *
         * @type number
         */
        this.trackingClickStart = 0;
        /**
         * The element being tracked for a click.
         *
         * @type EventTarget
         */
        this.targetElement = null;


        /**
         * X-coordinate of touch start event.
         *
         * @type number
         */
        this.touchStartX = 0;


        /**
         * Y-coordinate of touch start event.
         *
         * @type number
         */
        this.touchStartY = 0;


        /**
         * ID of the last touch, retrieved from Touch.identifier.
         *
         * @type number
         */
        this.lastTouchIdentifier = 0;


        /**
         * Touchmove boundary, beyond which a click will be cancelled.
         *
         * @type number
         */
        this.touchBoundary = options.touchBoundary || 10;


        /**
         * The FastClick layer.
         *
         * @type Element
         */
        this.layer = layer;

        /**
         * The minimum time between tap(touchstart and touchend) events
         *
         * @type number
         */
        this.tapDelay = options.tapDelay || 200;

        /**
         * The maximum time for a tap
         *
         * @type number
         */
        this.tapTimeout = options.tapTimeout || 700;

        if (FastClick.notNeeded(layer)) {
            return;
        }

        // Some old versions of Android don't have Function.prototype.bind
        function bind(method, context) {
            return function() { return method.apply(context, arguments); };
        }


        var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
        var context = this;
        for (var i = 0, l = methods.length; i < l; i++) {
            context[methods[i]] = bind(context[methods[i]], context);
        }

        // Set up event handlers as required
        if (deviceIsAndroid) {
            layer.addEventListener('mouseover', this.onMouse, true);
            layer.addEventListener('mousedown', this.onMouse, true);
            layer.addEventListener('mouseup', this.onMouse, true);
        }

        layer.addEventListener('click', this.onClick, true);
        layer.addEventListener('touchstart', this.onTouchStart, false);
        layer.addEventListener('touchmove', this.onTouchMove, false);
        layer.addEventListener('touchend', this.onTouchEnd, false);
        layer.addEventListener('touchcancel', this.onTouchCancel, false);

        // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
        // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
        // layer when they are cancelled.
        if (!Event.prototype.stopImmediatePropagation) {
            layer.removeEventListener = function(type, callback, capture) {
                var rmv = Node.prototype.removeEventListener;
                if (type === 'click') {
                    rmv.call(layer, type, callback.hijacked || callback, capture);
                } else {
                    rmv.call(layer, type, callback, capture);
                }
            };

            layer.addEventListener = function(type, callback, capture) {
                var adv = Node.prototype.addEventListener;
                if (type === 'click') {
                    adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
                        if (!event.propagationStopped) {
                            callback(event);
                        }
                    }), capture);
                } else {
                    adv.call(layer, type, callback, capture);
                }
            };
        }

        // If a handler is already declared in the element's onclick attribute, it will be fired before
        // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
        // adding it as listener.
        if (typeof layer.onclick === 'function') {

            // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
            // - the old one won't work if passed to addEventListener directly.
            oldOnClick = layer.onclick;
            layer.addEventListener('click', function(event) {
                oldOnClick(event);
            }, false);
            layer.onclick = null;
        }
    }

    /**
     * Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
     *
     * @type boolean
     */
    var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;

    /**
     * Android requires exceptions.
     *
     * @type boolean
     */
    var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;


    /**
     * iOS requires exceptions.
     *
     * @type boolean
     */
    var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;


    /**
     * iOS 4 requires an exception for select elements.
     *
     * @type boolean
     */
    var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);


    /**
     * iOS 6.0-7.* requires the target element to be manually derived
     *
     * @type boolean
     */
    var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);

    /**
     * BlackBerry requires exceptions.
     *
     * @type boolean
     */
    var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;

    /**
     * Determine whether a given element requires a native click.
     *
     * @param {EventTarget|Element} target Target DOM element
     * @returns {boolean} Returns true if the element needs a native click
     */
    FastClick.prototype.needsClick = function(target) {
        switch (target.nodeName.toLowerCase()) {

            // Don't send a synthetic click to disabled inputs (issue #62)
            case 'button':
            case 'select':
            case 'textarea':
                if (target.disabled) {
                    return true;
                }

                break;
            case 'input':

                // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
                if ((deviceIsIOS && target.type === 'file') || target.disabled) {
                    return true;
                }

                break;
            case 'label':
            case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
            case 'video':
                return true;
        }

        return (/\bneedsclick\b/).test(target.className);
    };


    /**
     * Determine whether a given element requires a call to focus to simulate click into element.
     *
     * @param {EventTarget|Element} target Target DOM element
     * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
     */
    FastClick.prototype.needsFocus = function(target) {
        switch (target.nodeName.toLowerCase()) {
            case 'textarea':
                return true;
            case 'select':
                return !deviceIsAndroid;
            case 'input':
                switch (target.type) {
                    case 'button':
                    case 'checkbox':
                    case 'file':
                    case 'image':
                    case 'radio':
                    case 'submit':
                        return false;
                }

                // No point in attempting to focus disabled inputs
                return !target.disabled && !target.readOnly;
            default:
                return (/\bneedsfocus\b/).test(target.className);
        }
    };


    /**
     * Send a click event to the specified element.
     *
     * @param {EventTarget|Element} targetElement
     * @param {Event} event
     */
    FastClick.prototype.sendClick = function(targetElement, event) {
        var clickEvent, touch;

        // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
        if (document.activeElement && document.activeElement !== targetElement) {
            document.activeElement.blur();
        }

        touch = event.changedTouches[0];

        // Synthesise a click event, with an extra attribute so it can be tracked
        clickEvent = document.createEvent('MouseEvents');
        clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
        clickEvent.forwardedTouchEvent = true;
        targetElement.dispatchEvent(clickEvent);
    };

    FastClick.prototype.determineEventType = function(targetElement) {

        //Issue #159: Android Chrome Select Box does not open with a synthetic click event
        if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
            return 'mousedown';
        }

        return 'click';
    };


    /**
     * @param {EventTarget|Element} targetElement
     */
    FastClick.prototype.focus = function(targetElement) {
        var length;

        // Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
        if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month' && targetElement.type !== 'email') {
            length = targetElement.value.length;
            targetElement.setSelectionRange(length, length);
        } else {
            targetElement.focus();
        }
    };


    /**
     * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
     *
     * @param {EventTarget|Element} targetElement
     */
    FastClick.prototype.updateScrollParent = function(targetElement) {
        var scrollParent, parentElement;

        scrollParent = targetElement.fastClickScrollParent;

        // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
        // target element was moved to another parent.
        if (!scrollParent || !scrollParent.contains(targetElement)) {
            parentElement = targetElement;
            do {
                if (parentElement.scrollHeight > parentElement.offsetHeight) {
                    scrollParent = parentElement;
                    targetElement.fastClickScrollParent = parentElement;
                    break;
                }

                parentElement = parentElement.parentElement;
            } while (parentElement);
        }

        // Always update the scroll top tracker if possible.
        if (scrollParent) {
            scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
        }
    };


    /**
     * @param {EventTarget} targetElement
     * @returns {Element|EventTarget}
     */
    FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {

        // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
        if (eventTarget.nodeType === Node.TEXT_NODE) {
            return eventTarget.parentNode;
        }

        return eventTarget;
    };


    /**
     * On touch start, record the position and scroll offset.
     *
     * @param {Event} event
     * @returns {boolean}
     */
    FastClick.prototype.onTouchStart = function(event) {
        var targetElement, touch, selection;

        // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
        if (event.targetTouches.length > 1) {
            return true;
        }

        targetElement = this.getTargetElementFromEventTarget(event.target);
        touch = event.targetTouches[0];

        if (deviceIsIOS) {

            // Only trusted events will deselect text on iOS (issue #49)
            selection = window.getSelection();
            if (selection.rangeCount && !selection.isCollapsed) {
                return true;
            }

            if (!deviceIsIOS4) {

                // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
                // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
                // with the same identifier as the touch event that previously triggered the click that triggered the alert.
                // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
                // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
                // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
                // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
                // random integers, it's safe to to continue if the identifier is 0 here.
                if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
                    event.preventDefault();
                    return false;
                }

                this.lastTouchIdentifier = touch.identifier;

                // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
                // 1) the user does a fling scroll on the scrollable layer
                // 2) the user stops the fling scroll with another tap
                // then the event.target of the last 'touchend' event will be the element that was under the user's finger
                // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
                // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
                this.updateScrollParent(targetElement);
            }
        }

        this.trackingClick = true;
        this.trackingClickStart = event.timeStamp;
        this.targetElement = targetElement;

        this.touchStartX = touch.pageX;
        this.touchStartY = touch.pageY;

        // Prevent phantom clicks on fast double-tap (issue #36)
        if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
            event.preventDefault();
        }

        return true;
    };


    /**
     * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
     *
     * @param {Event} event
     * @returns {boolean}
     */
    FastClick.prototype.touchHasMoved = function(event) {
        var touch = event.changedTouches[0],
            boundary = this.touchBoundary;

        if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
            return true;
        }

        return false;
    };


    /**
     * Update the last position.
     *
     * @param {Event} event
     * @returns {boolean}
     */
    FastClick.prototype.onTouchMove = function(event) {
        if (!this.trackingClick) {
            return true;
        }

        // If the touch has moved, cancel the click tracking
        if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
            this.trackingClick = false;
            this.targetElement = null;
        }

        return true;
    };


    /**
     * Attempt to find the labelled control for the given label element.
     *
     * @param {EventTarget|HTMLLabelElement} labelElement
     * @returns {Element|null}
     */
    FastClick.prototype.findControl = function(labelElement) {

        // Fast path for newer browsers supporting the HTML5 control attribute
        if (labelElement.control !== undefined) {
            return labelElement.control;
        }

        // All browsers under test that support touch events also support the HTML5 htmlFor attribute
        if (labelElement.htmlFor) {
            return document.getElementById(labelElement.htmlFor);
        }

        // If no for attribute exists, attempt to retrieve the first labellable descendant element
        // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
        return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
    };


    /**
     * On touch end, determine whether to send a click event at once.
     *
     * @param {Event} event
     * @returns {boolean}
     */
    FastClick.prototype.onTouchEnd = function(event) {
        var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;

        if (!this.trackingClick) {
            return true;
        }

        // Prevent phantom clicks on fast double-tap (issue #36)
        if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
            this.cancelNextClick = true;
            return true;
        }

        if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
            return true;
        }

        // Reset to prevent wrong click cancel on input (issue #156).
        this.cancelNextClick = false;

        this.lastClickTime = event.timeStamp;

        trackingClickStart = this.trackingClickStart;
        this.trackingClick = false;
        this.trackingClickStart = 0;

        // On some iOS devices, the targetElement supplied with the event is invalid if the layer
        // is performing a transition or scroll, and has to be re-detected manually. Note that
        // for this to function correctly, it must be called *after* the event target is checked!
        // See issue #57; also filed as rdar://13048589 .
        if (deviceIsIOSWithBadTarget) {
            touch = event.changedTouches[0];

            // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
            targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
            targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
        }

        targetTagName = targetElement.tagName.toLowerCase();
        if (targetTagName === 'label') {
            forElement = this.findControl(targetElement);
            if (forElement) {
                this.focus(targetElement);
                if (deviceIsAndroid) {
                    return false;
                }

                targetElement = forElement;
            }
        } else if (this.needsFocus(targetElement)) {

            // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
            // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
            if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
                this.targetElement = null;
                return false;
            }

            this.focus(targetElement);
            this.sendClick(targetElement, event);

            // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
            // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
            if (!deviceIsIOS || targetTagName !== 'select') {
                this.targetElement = null;
                event.preventDefault();
            }

            return false;
        }

        if (deviceIsIOS && !deviceIsIOS4) {

            // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
            // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
            scrollParent = targetElement.fastClickScrollParent;
            if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
                return true;
            }
        }

        // Prevent the actual click from going though - unless the target node is marked as requiring
        // real clicks or if it is in the allowlist in which case only non-programmatic clicks are permitted.
        if (!this.needsClick(targetElement)) {
            event.preventDefault();
            this.sendClick(targetElement, event);
        }

        return false;
    };


    /**
     * On touch cancel, stop tracking the click.
     *
     * @returns {void}
     */
    FastClick.prototype.onTouchCancel = function() {
        this.trackingClick = false;
        this.targetElement = null;
    };


    /**
     * Determine mouse events which should be permitted.
     *
     * @param {Event} event
     * @returns {boolean}
     */
    FastClick.prototype.onMouse = function(event) {

        // If a target element was never set (because a touch event was never fired) allow the event
        if (!this.targetElement) {
            return true;
        }

        if (event.forwardedTouchEvent) {
            return true;
        }

        // Programmatically generated events targeting a specific element should be permitted
        if (!event.cancelable) {
            return true;
        }

        // Derive and check the target element to see whether the mouse event needs to be permitted;
        // unless explicitly enabled, prevent non-touch click events from triggering actions,
        // to prevent ghost/doubleclicks.
        if (!this.needsClick(this.targetElement) || this.cancelNextClick) {

            // Prevent any user-added listeners declared on FastClick element from being fired.
            if (event.stopImmediatePropagation) {
                event.stopImmediatePropagation();
            } else {

                // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
                event.propagationStopped = true;
            }

            // Cancel the event
            event.stopPropagation();
            event.preventDefault();

            return false;
        }

        // If the mouse event is permitted, return true for the action to go through.
        return true;
    };


    /**
     * On actual clicks, determine whether this is a touch-generated click, a click action occurring
     * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
     * an actual click which should be permitted.
     *
     * @param {Event} event
     * @returns {boolean}
     */
    FastClick.prototype.onClick = function(event) {
        var permitted;

        // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
        if (this.trackingClick) {
            this.targetElement = null;
            this.trackingClick = false;
            return true;
        }

        // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
        if (event.target.type === 'submit' && event.detail === 0) {
            return true;
        }

        permitted = this.onMouse(event);

        // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
        if (!permitted) {
            this.targetElement = null;
        }

        // If clicks are permitted, return true for the action to go through.
        return permitted;
    };


    /**
     * Remove all FastClick's event listeners.
     *
     * @returns {void}
     */
    FastClick.prototype.destroy = function() {
        var layer = this.layer;

        if (deviceIsAndroid) {
            layer.removeEventListener('mouseover', this.onMouse, true);
            layer.removeEventListener('mousedown', this.onMouse, true);
            layer.removeEventListener('mouseup', this.onMouse, true);
        }

        layer.removeEventListener('click', this.onClick, true);
        layer.removeEventListener('touchstart', this.onTouchStart, false);
        layer.removeEventListener('touchmove', this.onTouchMove, false);
        layer.removeEventListener('touchend', this.onTouchEnd, false);
        layer.removeEventListener('touchcancel', this.onTouchCancel, false);
    };


    /**
     * Check whether FastClick is needed.
     *
     * @param {Element} layer The layer to listen on
     */
    FastClick.notNeeded = function(layer) {
        var metaViewport;
        var chromeVersion;
        var blackberryVersion;
        var firefoxVersion;

        // Devices that don't support touch don't need FastClick
        if (typeof window.ontouchstart === 'undefined') {
            return true;
        }

        // Chrome version - zero for other browsers
        chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [, 0])[1];

        if (chromeVersion) {

            if (deviceIsAndroid) {
                metaViewport = document.querySelector('meta[name=viewport]');

                if (metaViewport) {
                    // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
                    if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
                        return true;
                    }
                    // Chrome 32 and above with width=device-width or less don't need FastClick
                    if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
                        return true;
                    }
                }

                // Chrome desktop doesn't need FastClick (issue #15)
            } else {
                return true;
            }
        }

        if (deviceIsBlackBerry10) {
            blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);

            // BlackBerry 10.3+ does not require Fastclick library.
            // https://github.com/ftlabs/fastclick/issues/251
            if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
                metaViewport = document.querySelector('meta[name=viewport]');

                if (metaViewport) {
                    // user-scalable=no eliminates click delay.
                    if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
                        return true;
                    }
                    // width=device-width (or less than device-width) eliminates click delay.
                    if (document.documentElement.scrollWidth <= window.outerWidth) {
                        return true;
                    }
                }
            }
        }

        // IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
        if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
            return true;
        }

        // Firefox version - zero for other browsers
        firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [, 0])[1];

        if (firefoxVersion >= 27) {
            // Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896

            metaViewport = document.querySelector('meta[name=viewport]');
            if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
                return true;
            }
        }
        // IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
        // http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
        if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
            return true;
        }
        return false;
    };

    /**
     * Factory method for creating a FastClick object
     *
     * @param {Element} layer The layer to listen on
     * @param {Object} [options={}] The options to override the defaults
     */
    FastClick.attach = function(layer, options) {
        return new FastClick(layer, options);
    };
    if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {

        // AMD. Register as an anonymous module.
        define(function() {
            return FastClick;
        });
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = FastClick.attach;
        module.exports.FastClick = FastClick;
    } else {
        window.FastClick = FastClick;
    }
}());

调用插件

if ('addEventListener' in document) {
            document.addEventListener('DOMContentLoaded', function() {
                FastClick.attach(document.body);
            }, false);
        }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            width: 50px;
            height: 50px;
            background-color: pink;
        }
    </style>
    <script src="fastclick.js"></script>
</head>

<body>
    <div></div>
    <script>
        if ('addEventListener' in document) {
            document.addEventListener('DOMContentLoaded', function() {
                FastClick.attach(document.body);
            }, false);
        }
        var div = document.querySelector('div');
        div.addEventListener('click', function() {
            alert(11);
        })
    </script>
</body>

</html>

3. Swiper 插件

中文官网地址: https://www.swiper.com.cn/

  1. 引入插件相关文件
  2. 按照规定语法使用

4. 其他常见插件

5. 插件使用总结

  1. 确认插件实现的功能
  2. 去官网查看使用说明
  3. 下载插件
  4. 打开demo实例文件,查看需要引入的相关文件,并且引入
  5. 复制demo实例文件中的结构html,样式css以及js代码

6. 移动端视频插件 zy.media.js

H5 给我们提供了 video 标签,但是浏览器的支持情况不同。
不同的视频格式文件,我们可以通过source 解决。
但是外观样式,还有暂停,播放,全屏等功能我们只能自己写代码解决。
这个时候我们可以使用插件方式来制作。

demo 实例文件 代码如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link href="" rel="stylesheet">
    <style type="text/css">
        #modelView {
            background-color: #DDDDDD;
            z-index: 0;
            opacity: 0.7;
            height: 100%;
            width: 100%;
            position: relative;
        }
        
        .playvideo {
            padding-top: auto;
            z-index: 9999;
            position: relative;
            width: 300px;
            height: 200px;
        }
        
        .zy_media {
            z-index: 999999999
        }
    </style>
    <link rel="stylesheet" href="zy.media.min.css">
</head>

<body>

    <div class="playvideo">
        <div class="zy_media">
            <video data-config='{"mediaTitle": "测试视频--视频"}'>
        	<source src="mov.mp4" type="video/mp4">
      	  您的浏览器不支持HTML5视频
   	 </video>

        </div>
        <div id="modelView">&nbsp;</div>
    </div>
    <script src="zy.media.min.js"></script>
    <script>
        zymedia('video', {
            autoplay: true
        });
    </script>
</body>

</html>

index.html 代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="zy.media.min.css">
    <script src="zy.media.min.js"></script>
    <style type="text/css">
        #modelView {
            background-color: #DDDDDD;
            z-index: 0;
            opacity: 0.7;
            height: 100%;
            width: 100%;
            position: relative;
        }
        
        .playvideo {
            padding-top: auto;
            z-index: 9999;
            position: relative;
            width: 300px;
            height: 200px;
        }
        
        .zy_media {
            z-index: 999999999
        }
    </style>

</head>

<body>
    <div class="playvideo">
        <div class="zy_media">
            <video data-config='{"mediaTitle": "小蝴蝶"}'>
                    <source src="mov.mp4" type="video/mp4">
                    您的浏览器不支持HTML5视频
                </video>

        </div>
        <div id="modelView">&nbsp;</div>
    </div>
    <script>
        zymedia('video', {
            autoplay: false
        });
    </script>
</body>

</html>

zy.media.min.css

代码复制到编辑器后,可以全选按ctrl + k重排代码格式

body{margin:0}.zy_media{background:#000;position:relative}.zy_media video,.zy_media audio{width:100%;position:absolute;top:0;left:0;display:block}.zy_fullscreen{overflow:hidden}.zy_fullscreen .zy_media{position:fixed;left:0;top:0;right:0;bottom:0;z-index:1000}.zy_fullscreen .zy_wrap,.zy_fullscreen video{width:100%;height:100%}.zy_wrap{width:100%}.zy_title{height:34px;padding-left:10px;color:#fff;font-size:12px;line-height:34px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;background:rgba(0,0,0,.25);position:absolute;left:0;right:0;top:0;-webkit-transition:top .5s;transition:top .5s}.zy_media .dec_play,.zy_media .dec_loading,.zy_media .dec_error{margin:-32px 0 0 -31px;position:absolute;top:50%;left:50%}.zy_media .dec_play::before{width:60px;height:60px;content:'';border-radius:60px;border:#e5e5e4 1px solid;display:block}.zy_media .dec_play::after{width:0;height:0;content:'';border-color:transparent transparent transparent #e5e5e4;border-width:14px 20px;border-style:solid;position:absolute;top:16px;left:23px;z-index:2;display:block}.zy_media .dec_loading{width:62px;height:62px;-webkit-animation:ani_loading .6s infinite linear;-webkit-animation-fill-mode:forwards;animation:ani_loading .6s infinite linear;animation-fill-mode:forwards}@-webkit-keyframes ani_loading{100%{-webkit-transform:rotate(360deg)}}@keyframes ani_loading{100%{transform:rotate(360deg)}}.zy_media .dec_loading::before{width:7px;height:7px;content:'';border-radius:7px;background:#fff;opacity:.8;position:absolute;top:25px}.zy_media .dec_loading::after{width:48px;height:48px;content:'';border-radius:50px;border:7px solid #fff;opacity:.2;display:block}.zy_media .dec_error{width:62px;height:62px;margin-top:-53px;margin-left:-25px;white-space:nowrap;color:#fff;font-size:12px;text-align:center;position:absolute;top:50%;left:50%}.zy_controls{height:44px;background:rgba(0,0,0,.55);position:absolute;left:0;right:0;bottom:0;-webkit-transition:bottom .5s;transition:bottom .5s;display:-webkit-box;display:box;display:-webkit-flex;display:flex}.zy_playpause_btn{width:26px;height:30px;margin-right:4px;padding:13px 0 0 14px;position:relative}.zy_play::before{width:0;height:0;content:'';border-color:transparent transparent transparent #cbcbcb;border-width:8px 12px;border-style:solid;display:block}.zy_pause::before,.zy_pause::after{width:3px;height:14px;content:'';background:#cbcbcb;position:absolute;top:13px;left:14px}.zy_pause::after{left:22px}.zy_timeline{margin-right:10px;-webkit-box-flex:1;-webkit-flex:1 1 auto;flex:1 1 auto}.zy_timeline_slider{width:100%;height:1px;background:#999;position:relative;top:21px;left:0}.zy_timeline_buffering{width:100%;height:15px;top:-7px;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(.25,rgba(255,255,255,.15)),color-stop(.25,transparent),color-stop(.5,transparent),color-stop(.5,rgba(255,255,255,.15)),color-stop(.75,rgba(255,255,255,.15)),color-stop(.75,transparent),to(transparent));background-image:-webkit-linear-gradient(-45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(-45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:15px 15px;background-size:15px 15px;-webkit-animation:ani_buffering 2s linear infinite;animation:ani_buffering 2s linear infinite;position:absolute}@-webkit-keyframes ani_buffering{from{background-position:0 0}to{background-position:30px 0}}@keyframes ani_buffering{from{background-position:0 0}to{background-position:30px 0}}.zy_timeline_loaded{width:0;height:1px;background:#e5e5e5;position:absolute;top:0;left:0;z-index:1}.zy_timeline_current{width:0;height:1px;background:#ff6159;position:relative;z-index:2}.zy_timeline_handle{width:16px;height:16px;border-radius:16px;background:#e5e5e5;position:absolute;top:-8px;left:-8px;z-index:3}.zy_time{width:auto;height:44px;margin-right:5px;line-height:44px;font-size:11px;color:#999;text-align:center}.zy_time .zy_currenttime{color:#e5e5e5}.zy_fullscreen_btn{width:38px;height:44px;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaBAMAAAEsY2FrAAAAElBMVEX///+65XQCAAAABXRSTlMAHm1u3TG+li4AAAB5SURBVBgZBcGxbQNBEAQwPnCXC49TviU4UQnKx8ZP/62YVB58qQCIBwArGgAAwK4HkAUEgEXAEmBFG/AH+B0gN5BrQLwAAG4bXLOBewPXB/AGu6VtG4CeAUCdAaCcAVCcAQAAAAMAzrAD4IwdAM7PDgDOJwBt2wAA/9uDEjcL3fqtAAAAAElFTkSuQmCC);background-repeat:no-repeat;background-position:center;-webkit-background-size:16px;background-size:16px}.zy_unfullscreen{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaBAMAAAEsY2FrAAAAElBMVEX///+65XQCAAAABXRSTlMAHm1u3TG+li4AAAB5SURBVBgZBcGxDcMwEAQwGtH1QuD0WiGAB8gI39z+q4SEhR8AwALAwmAwgCAIS4AV0BYg7UAWEIttwNeA1x7gO8BrQDsAAGlBDpA3kOuAeIO4eDYZAM+WAeDZGQA8nwFo2w4AAAAAANq2A9D7AKDuA0C5D4DiPgDAH9lBEChOLXSRAAAAAElFTkSuQmCC)}

zy.media.min.js 代码如下:

! function() {
    function b(a, b) { return parseInt(a.style[b] || getComputedStyle(a, null).getPropertyValue(b)) }

    function c(a, b) { return new RegExp("(\\s|^)" + b + "(\\s|$)").test(a.className) }

    function d(a, b) { a.classList ? a.classList.add(b) : c(a, b) || (a.className += "" + b) }

    function e(a, b) { a.classList ? a.classList.remove(b) : c(a, b) && (a.className = a.className.replace(new RegExp("(\\s|^)" + b + "(\\s|$)"), " ").replace(/^\s+|\s+$/g, "")) }

    function f(a, b) {
        (!isFinite(a) || 0 > a) && (a = 0); var c = b.alwaysShowHours ? [0] : []; return Math.floor(a / 3600) % 24 && c.push(Math.floor(a / 3600) % 24), c.push(Math.floor(a / 60) % 60), c.push(Math.floor(a % 60)), c = c.join(":"), 1 == b.timeFormatType && (c = c.replace(/(:|^)([0-9])(?=:|$)/g, "$10$2")), c }

    function g() { return document.fullscreenElement || document.mozFullScreen || document.webkitIsFullScreen }

    function h(a) { var b, c; switch (a = a.toLowerCase().split("?")[0], b = a.substring(a.lastIndexOf(".") + 1), c = /mp4|m4v|ogg|ogv|m3u8|webm|webmv|wmv|mpeg|mov/gi.test(b) ? "video/" : "audio/", b) {
            case "mp4":
            case "m4v":
            case "m4a":
                return c + "mp4";
            case "webm":
            case "webma":
            case "webmv":
                return c + "webm";
            case "ogg":
            case "oga":
            case "ogv":
                return c + "ogg";
            case "m3u8":
                return "application/x-mpegurl";
            case "ts":
                return c + "mp2t";
            default:
                return c + b } }

    function i(a, b) { return a && !b ? h(a) : b && ~b.indexOf(";") ? b.substr(0, b.indexOf(";")) : b }

    function j(b, c, d) { var f, g, h, e = []; if (c.type)
            if ("string" == typeof c.type) e.push({ type: c.type, url: d });
            else
                for (f = 0; f < c.type.length; f++) e.push({ type: c.type[f], url: d });
        else if (null !== d) e.push({ type: i(d, b.getAttribute("type")), url: d });
        else
            for (f = 0; f < b.children.length; f++) g = b.children[f], 1 == g.nodeType && "source" == g.tagName.toLowerCase() && (d = g.getAttribute("src"), e.push({ type: i(d, g.getAttribute("type")), url: d })); if (a.features.isBustedAndroid && (b.canPlayType = function(a) { return /video\/(mp4|m4v)/i.test(a) ? "maybe" : "" }), a.features.isChromium && (b.canPlayType = function(a) { return /video\/(webm|ogv|ogg)/i.test(a) ? "maybe" : "" }), a.features.supportsCanPlayType)
            for (f = 0; f < e.length; f++)
                if ("video/m3u8" == e[f].type || "" !== b.canPlayType(e[f].type).replace(/no/, "") || "" !== b.canPlayType(e[f].type.replace(/mp3/, "mpeg")).replace(/no/, "") || "" !== b.canPlayType(e[f].type.replace(/m4a/, "mp4")).replace(/no/, "")) { h = !0; break }
        return h } var k, a = {};
    a.config = { type: "", mediaTitle: "", nativeControls: !1, autoplay: !1, preload: "none", videoWidth: "100%", videoHeight: "auto", aspectRation: 16 / 9, audioWidth: "100%", audioHeight: 44, autoLoop: !1, timeFormatType: 1, alwaysShowHours: !1, alwaysShowControls: !1, hideVideoControlsOnLoad: !1, enableFullscreen: !0, pauseOtherPlayers: !0, duration: 0, success: null, error: null },
        function(a) { var b = window.navigator.userAgent.toLowerCase(),
                c = document.createElement("video");
            a.isiOS = /iphone|ipod|ipad/i.test(b) && !window.MSStream, a.isAndroid = /android/i.test(b) && !window.MSStream, a.isBustedAndroid = /android 2\.[12]/i.test(b), a.isChromium = /chromium/i.test(b), a.hasTouch = "ontouchstart" in window, a.supportsCanPlayType = "undefined" != typeof c.canPlayType, a.isVendorBigPlay = /iphone/i.test(b) && !window.MSStream, a.isVendorControls = /baidu/i.test(b), a.isVendorFullscreen = /micromessenger|weibo/i.test(b), a.isVendorAutoplay = /v819mini/i.test(b) || a.isiOS, a.nativeFullscreenPrefix = function() { return c.requestFullScreen ? "" : c.webkitRequestFullScreen ? "webkit" : c.mozRequestFullScreen ? "moz" : c.msRequestFullScreen ? "ms" : "-" }(), a.hasOldNativeFullScreen = "-" == a.nativeFullscreenPrefix && c.webkitEnterFullscreen, a.hasOldNativeFullScreen && /mac os x 10_5/i.test(b) && (a.nativeFullscreenPrefix = "-", a.hasOldNativeFullScreen = !1) }(a.features = {}), k = 0, a.players = {}, a.MediaPlayer = function(b, c) { var e, f, g, i, d = this; if (!b.isInstantiated && (b.isInstantiated = !0, d.media = b, f = d.media.tagName.toLowerCase(), /audio|video/.test(f))) { d.isVideo = "video" === f, d.options = {}; for (e in a.config) d.options[e] = a.config[e]; try { for (e in c) d.options[e] = c[e];
                    g = JSON.parse(d.media.getAttribute("data-config")); for (e in g) d.options[e] = g[e] } catch (h) {}
                d.options.autoplay && (d.options.autoplay = !a.features.isVendorAutoplay), d.isVideo || (d.options.alwaysShowControls = !0), d.options.nativeControls || a.features.isVendorControls ? d.media.setAttribute("controls", "controls") : (i = d.media.getAttribute("src"), i = "" === i ? null : i, j(d.media, d.options, i) ? (d.id = "zym_" + k++, a.players[d.id] = d, d.init()) : alert("不支持此" + (d.isVideo ? "视" : "音") + "频")) } }, a.MediaPlayer.prototype = { isControlsVisible: !0, isFullScreen: !1, setPlayerSize: function(a) { var f, g, d = this,
                    e = b(d.container, "width");
                a > e && (d.width = e), d.enableAutoSize && (f = d.media.videoWidth, g = d.media.videoHeight, f && g && Math.abs(d.options.aspectRation - f / g) < .1 && (d.options.aspectRation = f / g), d.height = parseInt(e / d.options.aspectRation)), d.container.style.width = d.width + "px", d.media.style.height = d.container.style.height = d.height + "px" }, showControls: function() { var a = this;
                a.isControlsVisible || (a.controls.style.bottom = 0, a.options.mediaTitle && (a.title.style.top = 0), a.isControlsVisible = !0) }, hideControls: function() { var a = this;
                a.isControlsVisible && !a.options.alwaysShowControls && (a.controls.style.bottom = "-45px", a.options.mediaTitle && (a.title.style.top = "-35px"), a.isControlsVisible = !1) }, setControlsTimer: function(a) { var b = this;
                clearTimeout(b.controlsTimer), b.controlsTimer = setTimeout(function() { b.hideControls() }, a) }, updateTimeline: function(a) { var g, c = this,
                    d = void 0 !== a ? a.target : c.media,
                    e = null,
                    f = b(c.slider, "width");
                d.buffered && d.buffered.length > 0 && d.buffered.end && d.duration ? e = d.buffered.end(d.buffered.length - 1) / d.duration : void 0 !== d.bytesTotal && d.bytesTotal > 0 && void 0 !== d.bufferedBytes ? e = d.bufferedBytes / d.bytesTotal : a && a.lengthComputable && 0 !== a.total && (e = a.loaded / a.total), null !== e && (e = Math.min(1, Math.max(0, e)), c.loaded.style.width = f * e + "px", c.media.paused && setTimeout(function() { c.loaded.style.width = f * e + "px", c.updateTimeline() }, 300)), void 0 !== c.media.currentTime && c.media.duration && (g = Math.round(f * c.media.currentTime / c.media.duration), c.current.style.width = g + "px", c.handle.style.left = g - Math.round(b(c.handle, "width") / 2) + "px") }, updateTime: function() { var a = this;
                a.currentTime.innerHTML = f(a.media.currentTime, a.options), (a.options.duration > 1 || a.media.duration > 1) && (a.durationDuration.innerHTML = f(a.options.duration > 1 ? a.options.duration : a.media.duration, a.options)) }, enterFullScreen: function() { var c = this; if (c.normalHeight = b(c.container, "height"), c.normalWidth = b(c.container, "width"), "-" != a.features.nativeFullscreenPrefix) c.container[a.features.nativeFullscreenPrefix + "RequestFullScreen"]();
                else if (a.features.hasOldNativeFullScreen) return c.media.webkitEnterFullscreen(), void 0;
                d(document.documentElement, "zy_fullscreen"), c.media.style.width = c.container.style.width = "100%", c.media.style.height = c.container.style.height = "100%", d(c.fullscreenBtn, "zy_unfullscreen"), c.isFullScreen = !0 }, exitFullScreen: function() { var b = this;
                (g() || b.isFullScreen) && ("-" != a.features.nativeFullscreenPrefix ? document[a.features.nativeFullscreenPrefix + "CancelFullScreen"]() : a.features.hasOldNativeFullScreen && document.webkitExitFullscreen()), e(document.documentElement, "zy_fullscreen"), b.media.style.width = b.container.style.width = b.normalWidth + "px", b.media.style.height = b.container.style.height = b.normalHeight + "px", e(b.fullscreenBtn, "zy_unfullscreen"), b.isFullScreen = !1 }, buildContainer: function() { var a = this;
                a.container = a.media.parentNode, a.container.style.overflow = "hidden", a.container.style.height = (a.isVideo ? b(a.container, "width") / a.options.aspectRation : a.options.audioHeight) + "px", a.container.innerHTML = '<div class="zy_wrap"></div><div class="zy_controls"></div>' + (a.options.mediaTitle ? '<div class="zy_title">' + a.options.mediaTitle + "</div>" : ""), a.title = a.container.querySelector(".zy_title"), a.media.setAttribute("preload", a.options.preload), a.container.querySelector(".zy_wrap").appendChild(a.media), a.controls = a.container.querySelector(".zy_controls"), a.isVideo && (a.width = a.options.videoWidth, a.height = a.options.videoHeight, "100%" == a.width && "auto" == a.height && (a.enableAutoSize = !0), a.setPlayerSize(a.width, a.height)) }, buildPlaypause: function() {
                function c(c) {
                    (a.media.isUserClick || a.options.autoplay) && ("play" === c ? (e(b, "zy_play"), d(b, "zy_pause")) : (e(b, "zy_pause"), d(b, "zy_play"))) } var a = this,
                    b = document.createElement("div");
                b.className = "zy_playpause_btn zy_play", a.controls.appendChild(b), b.addEventListener("click", function() { a.media.isUserClick = !0, a.media.paused ? (a.media.play(), a.media.paused || a.options.alwaysShowControls || a.setControlsTimer(3e3)) : a.media.pause() }), a.media.addEventListener("play", function() { c("play") }), a.media.addEventListener("playing", function() { c("play") }), a.media.addEventListener("pause", function() { c("pse") }), a.media.addEventListener("paused", function() { c("pse") }) }, buildTimeline: function() { var e, g, h, i, j, c = this,
                    d = document.createElement("div");
                d.className = "zy_timeline", d.innerHTML = '<div class="zy_timeline_slider"><div class="zy_timeline_buffering" style="display:none"></div><div class="zy_timeline_loaded"></div><div class="zy_timeline_current"></div><div class="zy_timeline_handle"></div></div>', c.controls.appendChild(d), c.slider = d.children[0], c.buffering = c.slider.children[0], c.loaded = c.slider.children[1], c.current = c.slider.children[2], c.handle = c.slider.children[3], e = !1, g = c.slider.offsetLeft, h = b(c.slider, "width"), i = b(c.handle, "width") / 2, j = function(a) { var d, b = 0;
                    d = a.changedTouches ? a.changedTouches[0].pageX : a.pageX, c.media.duration && (g > d ? d = g : d > h + g && (d = h + g), c.handle.style.left = d - i - g + "px", b = (d - g) / h * c.media.duration, c.currentTime.innerHTML = f(c.media.currentTime, c.options), e && b !== c.media.currentTime && (c.media.currentTime = b)) }, a.features.hasTouch ? c.slider.addEventListener("touchstart", function(a) { e = !0, j(a), g = c.slider.offsetLeft, h = b(c.slider, "width"), c.slider.addEventListener("touchmove", j), c.slider.addEventListener("touchend", function() { e = !1, c.slider.removeEventListener("touchmove", j) }) }) : c.slider.addEventListener("mousedown", function(a) { e = !0, j(a), g = c.slider.offsetLeft, h = b(c.slider, "width"), c.slider.addEventListener("mousemove", j), c.slider.addEventListener("mouseup", function() { e = !1, c.slider.addEventListener("mousemove", j) }) }), c.slider.addEventListener("mouseenter", function() { c.slider.addEventListener("mousemove", j) }), c.slider.addEventListener("mouseleave", function() { e || c.slider.removeEventListener("mousemove", j) }), c.media.addEventListener("timeupdate", function(a) { c.updateTimeline(a) }) }, buildTime: function() { var a = this,
                    b = document.createElement("div");
                b.className = "zy_time", b.innerHTML = '<span class="zy_currenttime">' + f(0, a.options) + "</span>/" + '<span class="zy_duration">' + f(a.options.duration, a.options) + "</span>", a.controls.appendChild(b), a.currentTime = b.children[0], a.durationDuration = b.children[1], a.media.addEventListener("timeupdate", function() { a.updateTime() }) }, buildFullscreen: function() { var c, b = this; "-" != a.features.nativeFullscreenPrefix && (c = function() { b.isFullScreen && (g() || b.exitFullScreen()) }, document.addEventListener(a.features.nativeFullscreenPrefix + "fullscreenchange", c)), b.fullscreenBtn = document.createElement("div"), b.fullscreenBtn.className = "zy_fullscreen_btn", b.controls.appendChild(b.fullscreenBtn), b.fullscreenBtn.addEventListener("click", function() { "-" != a.features.nativeFullscreenPrefix && g() || b.isFullScreen ? b.exitFullScreen() : b.enterFullScreen() }) }, buildDec: function() { var d, e, b = this,
                    c = document.createElement("div");
                c.className = "dec_loading", c.style.display = "none", b.container.appendChild(c), d = document.createElement("div"), d.className = "dec_error", d.style.display = "none", d.innerHTML = "播放异常", b.container.appendChild(d), e = document.createElement("div"), a.features.isVendorBigPlay || (e.className = "dec_play", b.container.appendChild(e), e.addEventListener("click", function() { b.media.isUserClick = !0, b.media.play(), b.media.paused || b.options.alwaysShowControls || b.setControlsTimer(3e3) })), b.media.addEventListener("play", function() { b.media.isUserClick && (e.style.display = "none", c.style.display = "", b.buffering.style.display = "none") }), b.media.addEventListener("playing", function() { e.style.display = "none", c.style.display = "none", b.buffering.style.display = "none", d.style.display = "none" }), b.media.addEventListener("seeking", function() { c.style.display = "", e.style.display = "none", b.buffering.style.display = "" }), b.media.addEventListener("seeked", function() { c.style.display = "none", b.buffering.style.display = "none" }), b.media.addEventListener("pause", function() { e.style.display = "" }), b.media.addEventListener("waiting", function() { c.style.display = "", e.style.display = "none", b.buffering.style.display = "" }), b.media.addEventListener("error", function(a) { c.style.display = "none", e.style.display = "", b.buffering.style.display = "none", b.media.pause(), d.style.display = "", "function" == typeof b.options.error && b.options.error(a) }) }, init: function() { var d, b = this,
                    c = ["Container", "Playpause", "Timeline", "Time"]; for (b.options.enableFullscreen && !a.features.isVendorFullscreen && b.isVideo && c.push("Fullscreen"), b.isVideo && c.push("Dec"), d = 0; d < c.length; d++) try { b["build" + c[d]]() } catch (e) {}
                b.isVideo && (a.features.hasTouch ? b.media.addEventListener("click", function() { b.isControlsVisible ? b.hideControls() : (b.showControls(), b.media.paused || b.options.alwaysShowControls || b.setControlsTimer(3e3)) }) : (b.media.addEventListener("click", function() { b.media.paused ? b.media.play() : b.media.pause() }), b.container.addEventListener("mouseenter", function() { b.showControls(), b.options.alwaysShowControls || b.setControlsTimer(3e3) }), b.container.addEventListener("mousemove", function() { b.showControls(), b.options.alwaysShowControls || b.setControlsTimer(3e3) })), b.options.hideVideoControlsOnLoad && b.hideControls(), b.media.addEventListener("loadedmetadata", function() { b.enableAutoSize && setTimeout(function() { isNaN(b.media.videoHeight) || b.setPlayerSize() }, 50) })), b.media.addEventListener("play", function() { var c, d; for (d in a.players)
                        if (c = a.players[d], c.id != b.id && b.options.pauseOtherPlayers && !c.paused && !c.ended) try { c.media.pause() } catch (e) {} }), window.addEventListener("orientationchange", function() { setTimeout(function() { b.setPlayerSize() }, 500) }), b.media.addEventListener("ended", function(a) { b.media.currentTime = 0, b.options.autoLoop ? b.media.play() : (b.isVideo && setTimeout(function() { b.container.querySelector(".dec_loading").style.display = "none" }, 20), b.media.pause()), b.updateTimeline(a) }), b.media.addEventListener("loadedmetadata", function() { b.updateTime() }), b.options.autoplay && (b.media.isUserClick = !1, b.media.play()), "function" == typeof b.options.success && b.options.success(b.media) } }, window.zymedia = function(b, c) { "string" == typeof b ? [].forEach.call(document.querySelectorAll(b), function(b) { new a.MediaPlayer(b, c) }) : new a.MediaPlayer(b, c) } }();

四、移动端常用开发框架

1. 框架

框架,顾名思义就是一套架构,它会基于自身的特点向用户提供一套较为完整的解决方案。框架的控制权在框架本身,使用者要按照框架所规定的某种规范进行开发。
插件一般是为了解决某个问题而专门存在,其功能单一,并且比较小。

前端常用的框架有 Bootstrap、Vue、Angular、React 等。既能开发PC端,也能开发移动端

前端常用的移动端插件有 swiper、superslide、iscroll等。

框架: 大而全,一整套解决方案
插件: 小而专一,某个功能的解决方案

2. Bootstrap

Bootstrap 是一个简洁、直观、强悍的前端开发框架,它让 web 开发更迅速、简单。
它能开发PC端,也能开发移动端

Bootstrap JS插件使用步骤:

  1. 引入相关js 文件
  2. 复制HTML 结构
  3. 修改对应样式
  4. 修改相应JS 参数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凡小多

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值