移动端常用插件

一、什么是插件

移动端要求的是快速开发,所以我们经常会借助于一些插件来帮我们完成操作,那么什么是插件呢?
简单来说 js 插件就是一个 js 文件,它遵循一定规范编写,方便程序展示效果,拥有特定功能且方便调用,如轮播图和瀑布流插件。
它一般是为了解决某个问题而专门存在的,功能单一且非常小!

二、fastclick 插件

移动端 click 事件会有 300ms 的延迟,原因是移动端屏幕双击会缩放页面。fastclick 插件用于解决 300ms 延迟问题。
GitHub 官网地址:https://github.com/ftlabs/fastclick

1.使用步骤

① 浏览器打开上面的官网,找到 lib 目录并点击

在这里插入图片描述
② 找到 fastclick.js 点击

在这里插入图片描述
③ 打开后复制全部代码

这些代码我已经复制好了,在下面的插件源码里面!
在这里插入图片描述
④ 项目中新建一个 js 文件把以上代码粘贴进去,并在 html 中引入

<script src="fastclick.js"></script>

⑤ 返回 GitHub 主页往下翻找到 Usage 下的这段代码复制上,粘贴到我们的 index.js 文件内
在这里插入图片描述

2.插件源码

① index.js

if ('addEventListener' in document) {
	document.addEventListener('DOMContentLoaded', function() {
		FastClick.attach(document.body);
	}, false);
}

② 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;
	}
}());

三、Swiper 插件

Swiper 是帮助我们写轮播图的一个插件!
中文官网网址:http://www.swiper.com.cn/

1.使用步骤

① 获取 Swiper,下载
在这里插入图片描述

② CSS 文件和 JS 文件在 dist 文件夹下,直接拿到我们的项目中去
打开之后,swiper.css 和 swiper.min.css 文件任选一个,它们的区别就是后者文件更小,所以我们选择 swiper.min.css。
JS 文件同理,把它们拿到项目文件夹下。

③ 在 HTML 页面中引入 CSS 文件和 JS 文件
注意我们的 index.js 是依赖于现在这个 js 文件的,所以把 index.js 放到下面。

④ 打开 demos 文件夹,选择想要的模型右键查看源码
找到 body 部分选中并复制,直接将标签代码粘贴到我们轮播图模块的位置,注意不要更改类名。
在这里插入图片描述
继续回到刚才源码页面,找到 CSS 里面的 swiper 相关类,选中并复制,直接粘贴到页面 CSS 文件 index.css 里面。
在这里插入图片描述
同样,JS代码也需复制,然后粘贴到 index.js 文件里面,注意先添加 window 加载事件。
在这里插入图片描述
demos 文件夹下有许多不同编号的网页文件,自动切换效果的编号是280!

2.修改参数

① 想要修改 index.js 里面的参数值,依然在中文网站首页找到 API 文档,这里面会告诉我们各个模块及参数都是什么样的功能,哪里不会点哪里,知道了含义,就可以自己更改参数值了;
② 想要修改 index.css 里面的参数值,最简单的方法就是自己专门再写一个样式把原来那个覆盖掉,想要覆盖掉之前的样式,就必须提高权重,属性值后面加上 !important 即可。

四、zy.media.js 插件

zy.media.js 是移动端的一个视频插件!
H5 给我们提供了 video 标签,但是浏览器的支持情况不同,不同的格式的视频文件,我们可以通过
source 解决,但是外观样式,还有暂停、播放、全屏等功能我们只能自己写代码解决,这个时候我们可以使用插件的方式来实现。
GitHub 官方网址,https://github.com/ireaderlab/zyMedia

1.使用步骤

在这里插入图片描述

2.插件源码

① zy.media.css

body { margin: 0 }

/* Hide iOS controls */
video::-webkit-media-controls-panel { -webkit-appearance: none; display: none !important }
video::-webkit-media-controls-play-button { -webkit-appearance: none; display: none !important }
video::-webkit-media-controls-start-playback-button { -webkit-appearance: none; display: none !important }

/* opacity:0 is for fix controls bar display background in iOS 10.0.1 UIWebView */
video::-webkit-media-controls, video::-webkit-media-controls-container, video::-webkit-media-controls-enclosure { opacity: 0; -webkit-appearance: none; display: none !important }

/* zy.media style */
.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: -21px 0 0 -21px; position: absolute; top: 50%; left: 50% }
.zy_media .dec_play::before { width: 40px; height: 40px; 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: 10px 15px; border-style: solid; position: absolute; top: 11px; left: 16px; z-index: 2; display: block }
.zy_media .dec_loading { width: 42px; height: 42px; -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: 4px; height: 4px; content: ''; border-radius: 4px; background: #fff; opacity: .8; position: absolute; top: 25px }
.zy_media .dec_loading::after { width: 34px; height: 34px; content: ''; border-radius: 50px; border: 4px solid #fff; opacity: .2; display: block }
.zy_media .dec_error { width: 120px; height: 62px; margin-top: -53px; margin-left: -60px; white-space: nowrap; color: #fff; font-size: 12px; text-align: center; position: absolute; top: 50%; left: 50%; }

/* 控制栏 */
.zy_controls { height: 44px; position: absolute; left: 0; right: 0; bottom: 0; z-index: 10; -webkit-transition: bottom .5s; transition: bottom .5s; display: -webkit-box; display: box; display: -webkit-flex; display: flex }

/* 播放、暂停按钮 */
.zy_playpause_btn_play, .zy_playpause_btn_pause { width: 44px; height: 44px; background-position: center; background-repeat: no-repeat; background-size: 7px 8px; position: relative }
.zy_playpause_btn_play { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAaCAYAAACtv5zzAAABJklEQVRIDWNgAIL///8HA/E5IP4AxDuBOAqIGUFyFAOgQSDDsYFTQEFbalhwHpvpSGJrgWwVsi0Cav6NZBgu5i+gRB8QC5JsES4TcYi/BYoXADEr0RbhMIiQ8G2ggkCiLCFkEgH5Q0B5U7wWETCAGOl/QEVLgFgOq0XEmECkmu9Ada1AzItiEZGaSVH2Eqg4HYiZQRYxgnSi2Eg9zn6gUUG0tADk1Km0tuAFE/VCBKtJTLS2YDUtg2gr0E/BtPDBK6DBmUDsz8jI+BNU2VALgDJaGxBTPaOBioqlQEyTooJmhR2ouA7CmjDRBYEKSQHvgIoLgZikCucnETaAqsx+ICaryjxIwAKKK31QswWUEtABdZotoDgBmhwCxBeA+BMQHwZiqjW8AG00IoLJ8efoAAAAAElFTkSuQmCC) }
.zy_playpause_btn_pause { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAYAgMAAACD0OXYAAAADFBMVEUAAAD///84wDuoAAAAA3RSTlMASePizoNQAAAAJElEQVQI12PIc2BgkJ7AsL+BgUH/AcP/AwwM9h8GBwV1EsSBALN6Qeeo4L6aAAAAAElFTkSuQmCC) }

/* 时间线操作区 */
.zy_timeline { margin-left: 14px; margin-right: 14px; -webkit-box-flex: 1; -webkit-flex: 1 1 auto; flex: 1 1 auto }
.zy_timeline_slider { width: 100%; height: 2px; background: rgba(255, 255, 255, .5); 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: 2px; background: #fff; position: absolute; top: 0; left: 0; z-index: 1 }
.zy_timeline_current { width: 0; height: 2px; background: #ff6159; position: relative; z-index: 2 }
.zy_timeline_handle { width: 8px; height: 8px; border-radius: 8px; background: #e5e5e5; position: absolute; top: -3px; left: -4px; z-index: 3 }

/* 时间展示 */
.zy_time, .zy_currenttime { width: auto; height: 44px; line-height: 44px; font-size: 10px; color: #e5e5e5; text-align: center }
.zy_time:last-child { padding-right: 14px }

/* 全屏控制按钮 */
.zy_fullscreen_btn { width: 38px; height: 44px; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaBAMAAABbZFH9AAAAFVBMVEUAAAD///9Iz20EAAAABnRSTlMAhcTz+f7GdglEAAAASklEQVQY02NQTUtLc2RgYBAB0kEMYUAyGcgzA9KpDGlIcmkMaQkMMMBGPs/NAc5jSWEQFoDzGA0ZaAFQbUC1nTo+Qg0l1BBECV0AMZkjVRJO9QcAAAAASUVORK5CYII=); background-repeat: no-repeat; background-position: center; background-size: 10px 10px }
.zy_unfullscreen { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAbCAMAAABY1h8eAAAAgVBMVEUAAAD///9d3yJTAAAAKnRSTlMAAQMECw8XHCAhIzdugYWRmpydn6SmxMnX3+Pn6Ovs8PLz9Pb4+fv8/f6584ZkAAAAl0lEQVQoz6XSzQ6CMBAE4K3/FaxSBBUVRK3IvP8DepAmJu1wca5fJpvsrohOhEZ3yBTDBIClmnk1rQlQ2UEdnFAFIFTjOCjBrzL0GhHjANpsvfUjzb6UP7J7v5r6Up2Omwg+/HwsQrx6O0xCrACgWK50xOQM8APXwJ5qA8wt0zswU0xv6KbC1Dy3v6/DT5jKiOZ0ySrN1x8orxmvk2ibBAAAAABJRU5ErkJggg==) }

.zy_playback_rate { width: 60px; margin-right: 6px; text-align: center; position: relative; }
.zy_playback_rate .zy_playback_rate_val { height: 44px; line-height: 44px; color: #e5e5e5; font-size: 10px; }
.zy_playback_rate .zy_playback_rate_option { width: 60px; margin: 0; padding: 0; font-size: 12px; color: #fff; border-radius: 2px; background: rgba(0, 0, 0, .6); position: absolute; left: 0; bottom: 44px; list-style: none; display: none; }
.zy_playback_rate .zy_playback_rate_option li { line-height: 30px; }
.zy_playback_rate .zy_playback_rate_option li.active { color: #1589FF; }

② zy.media.js

/*
 *
 * zy.media.js
 * HTML5 <video> and <audio> native player
 *
 * Copyright 2016-2019, iReader FE(掌阅书城研发--前端组)
 * License: MIT
 *
 */
;(function() {
	var zyMedia = {}

	// Default config
	zyMedia.config = {
		// Overrides the type specified, for dynamic instantiation
		type: '',
		// Set media title
		mediaTitle: '',
		// Force native controls
		nativeControls: false,
		// Autoplay
		autoplay: false,
		// Preload, not 'auto', in native app of xiaomi HM 1SW,
		// the images does not synchronize with sound of video which is cross-domain
		preload: 'none',
		// Video width
		videoWidth: '100%',
		// Video height
		videoHeight: 'auto',
		// Aspect ration 16:9
		aspectRation: 16 / 9,
		// Audio width
		audioWidth: '100%',
		// Audio height
		audioHeight: 44,
		// AutoLoop, true for infinite loop, false for rewind to beginning when media ends
		autoLoop: false,
		// Show poster again after video ended
		showPosterAfterEnd: false,
		// Time format to show. Default 1 for 'mm:ss', 2 for 'm:s'
		timeFormatType: 1,
		// Forces the hour marker (##:00:00)
		alwaysShowHours: false,
		// Hide controls when playing and mouse is not over the video
		alwaysShowControls: false,
		// Hide the video control when loading
		hideVideoControlsOnLoad: false,
		// Show fullscreen button
		enableFullscreen: true,
		// When this player starts, it will pause other players
		pauseOtherPlayers: true,
		// When page's visibilityState is hidden, pause all media
		enableVisibilityState: true,
		// Media duration
		duration: 0,
		// Sucess callback
		success: null,
		// Error callback
		error: null,
		// ux before play,media will can't play if return true
		beforePlay: null,
		// Show playback rate
		showPlaybackRate: true
	}

	// Feature detect
	;(function(t) {
		var ua = window.navigator.userAgent.toLowerCase()
		var v = document.createElement('video')

		t.isBustedAndroid = /android 2\.[12]/i.test(ua)
		t.isChromium = /chromium/i.test(ua)

		t.hasTouch = 'ontouchstart' in window
		t.supportsCanPlayType = typeof v.canPlayType !== 'undefined'

		// Detect playsinline. False in iOS 11 UIWebView
		t.isPlaysInline = matchMedia('(-webkit-video-playable-inline)').matches
		t.iPhoneVersion = ua.match(/iPhone OS (\d+)_?/i)
		// Vendor for no big play button
		t.isVendorBigPlay = (function() {
			if (window.MSStream) {
				return false
			}

			return false
		})()

		// Vendor for no controls bar
		t.isVendorControls = /baidu/i.test(ua) && !/baiduboxapp/i.test(ua)

		// Prefix of current working browser
		t.nativeFullscreenPrefix = (function() {
			if (v.requestFullScreen) {
				return ''
			} else if (v.webkitRequestFullScreen) {
				return 'webkit'
			} else if (v.mozRequestFullScreen) {
				return 'moz'
			} else if (v.msRequestFullScreen) {
				return 'ms'
			}
			return '-'
		})()

		if (typeof document.visibilityState != 'undefined') {
			t.vChange = 'visibilitychange'
			t.vState = 'visibilityState'
		} else if (typeof document.webkitVisibilityState != 'undefined') {
			t.vChange = 'webkitvisibilitychange'
			t.vState = 'webkitVisibilityState'
		} else {
			t.vChange = ''
			t.vState = ''
		}

		// None-standard
		t.hasOldNativeFullScreen =
			t.nativeFullscreenPrefix == '-' && v.webkitEnterFullscreen

		// OS X 10.5 can't do this even if it says it can
		if (t.hasOldNativeFullScreen && /mac os x 10_5/i.test(ua)) {
			t.nativeFullscreenPrefix = '-'
			t.hasOldNativeFullScreen = false
		}
	})((zyMedia.features = {}))

	// Get style
	function _css(el, property) {
		return parseInt(getComputedStyle(el, null).getPropertyValue(property))
	}
	// Add class
	function _addClass(el, token) {
		el.classList.add(token)
	}

	// Remove class
	function _removeClass(el, token) {
		el.classList.remove(token)
	}

	// Get time format
	function timeFormat(time, options) {
		// Video's duration is Infinity in GiONEE(金立) device
		if (!isFinite(time) || time < 0) {
			time = 0
		}
		// Get hours
		var _time = options.alwaysShowHours ? [0] : []
		if (Math.floor(time / 3600) % 24) {
			_time.push(Math.floor(time / 3600) % 24)
		}
		// Get minutes
		_time.push(Math.floor(time / 60) % 60)
		// Get seconds
		_time.push(Math.floor(time % 60))
		_time = _time.join(':')
		// Fill '0'
		if (options.timeFormatType == 1) {
			_time = _time.replace(/(:|^)([0-9])(?=:|$)/g, '$10$2')
		}

		return _time
	}

	// Report whether or not the document in fullscreen mode
	function isInFullScreenMode() {
		return (
			document.fullscreenElement ||
			document.mozFullScreen ||
			document.webkitIsFullScreen
		)
	}

	// Get media type from file extension
	function getTypeFromFileExtension(url) {
		url = url.toLowerCase().split('?')[0]
		var _ext = url.substring(url.lastIndexOf('.') + 1)
		var _av = /mp4|m4v|ogg|ogv|m3u8|webm|webmv|wmv|mpeg|mov/gi.test(_ext)
			? 'video/'
			: 'audio/'

		switch (_ext) {
			case 'mp4':
			case 'm4v':
			case 'm4a':
				return _av + 'mp4'
			case 'webm':
			case 'webma':
			case 'webmv':
				return _av + 'webm'
			case 'ogg':
			case 'oga':
			case 'ogv':
				return _av + 'ogg'
			case 'm3u8':
				return 'application/x-mpegurl'
			case 'ts':
				return _av + 'mp2t'
			default:
				return _av + _ext
		}
	}

	// Get media type
	function getType(url, type) {
		// If no type is specified, try to get from the extension
		if (url && !type) {
			return getTypeFromFileExtension(url)
		} else {
			// Only return the mime part of the type in case the attribute contains the codec
			// see https://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
			// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
			if (type && ~type.indexOf(';')) {
				return type.substr(0, type.indexOf(';'))
			} else {
				return type
			}
		}
	}

	// Detect if current type is supported
	function detectType(media, options, src) {
		var mediaFiles = []
		var i
		var n
		var isCanPlay

		// Get URL and type
		if (options.type) {
			// Accept either string or array of types
			if (typeof options.type == 'string') {
				mediaFiles.push({
					type: options.type,
					url: src
				})
			} else {
				for (i = 0; i < options.type.length; i++) {
					mediaFiles.push({
						type: options.type[i],
						url: src
					})
				}
			}
		} else if (src !== null) {
			// If src attribute
			mediaFiles.push({
				type: getType(src, media.getAttribute('type')),
				url: src
			})
		} else {
			// If <source> elements
			for (i = 0; i < media.children.length; i++) {
				n = media.children[i]

				if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
					src = n.getAttribute('src')
					mediaFiles.push({
						type: getType(src, n.getAttribute('type')),
						url: src
					})
				}
			}
		}

		// For Android which doesn't implement the canPlayType function (always returns '')
		if (zyMedia.features.isBustedAndroid) {
			media.canPlayType = function(type) {
				return /video\/(mp4|m4v)/i.test(type) ? 'maybe' : ''
			}
		}
		// For Chromium to specify natively supported video codecs (i.e. WebM and Theora)
		if (zyMedia.features.isChromium) {
			media.canPlayType = function(type) {
				return /video\/(webm|ogv|ogg)/i.test(type) ? 'maybe' : ''
			}
		}

		if (zyMedia.features.supportsCanPlayType) {
			for (i = 0; i < mediaFiles.length; i++) {
				// Normal detect
				if (
					mediaFiles[i].type == 'video/m3u8' ||
					media.canPlayType(mediaFiles[i].type).replace(/no/, '') !==
						'' ||
					// For Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
					media
						.canPlayType(mediaFiles[i].type.replace(/mp3/, 'mpeg'))
						.replace(/no/, '') !== '' ||
					// For m4a supported by detecting mp4 support
					media
						.canPlayType(mediaFiles[i].type.replace(/m4a/, 'mp4'))
						.replace(/no/, '') !== ''
				) {
					isCanPlay = true
					break
				}
			}
		}

		return isCanPlay
	}

	// Mediaplayer instance No
	var zymIndex = 0
	// Store Mediaplayer instance
	zyMedia.players = {}

	// Constructor, MediaPlayer
	zyMedia.MediaPlayer = function(media, option) {
		var t = this
		var i

		// Make sure it can't be instantiated again
		if (media.isInstantiated) {
			return
		} else {
			media.isInstantiated = true
		}

		t.media = media

		// Detect video or audio
		var _tagName = t.media.tagName.toLowerCase()
		if (!/audio|video/.test(_tagName)) return

		t.isVideo = _tagName === 'video'

		// Extend options
		t.options = {}
		for (i in zyMedia.config) {
			t.options[i] = zyMedia.config[i]
		}

		try {
			for (i in option) {
				t.options[i] = option[i]
			}
			// Data-config has the highest priority
			var config = JSON.parse(t.media.getAttribute('data-config'))
			for (i in config) {
				t.options[i] = config[i]
			}
		} catch (exp) {}

		// Set preload is auto for media can't play in iOS 11+ UIWebView
		if (
			t.options.preload == 'none' &&
			zyMedia.features.iPhoneVersion &&
			zyMedia.features.iPhoneVersion[1] >= 11
		) {
			t.options.preload = 'auto'
		}

		if (!t.isVideo) {
			t.options.alwaysShowControls = true
		}

		if (t.options.nativeControls || zyMedia.features.isVendorControls) {
			// Use native controls
			t.media.setAttribute('controls', 'controls')
			if (zyMedia.features.isPlaysInline) {
				t.media.setAttribute('playsinline', '')
			}
			// reset position: absolute -> relative
			t.media.style.position = 'relative'
		} else {
			var src = t.media.getAttribute('src')
			src = src === '' ? null : src

			if (detectType(t.media, t.options, src)) {
				// Unique ID
				t.id = 'zym_' + zymIndex++
				zyMedia.players[t.id] = t
				t.init()
			} else {
				alert('不支持此' + (t.isVideo ? '视' : '音') + '频')
			}
		}
	}

	zyMedia.MediaPlayer.prototype = {
		isControlsVisible: true,
		isFullScreen: false,

		setPlayerSize: function(width, height) {
			var t = this

			// Ignore in fullscreen status
			if (isInFullScreenMode() || t.isFullScreen) {
				return
			}

			// Set t.width
			if (width == undefined || width == '100%') {
				t.width = _css(t.container, 'width')
			}

			// Set t.height
			if (height == undefined || height == 'auto') {
				var nativeWidth = t.media.videoWidth
				var nativeHeight = t.media.videoHeight
				// Uniform scale
				if (nativeWidth && nativeHeight) {
					if (
						Math.abs(
							t.options.aspectRation - nativeWidth / nativeHeight
						) < 0.1
					) {
						t.options.aspectRation = nativeWidth / nativeHeight
					}
				}
				t.height = parseInt(t.width / t.options.aspectRation)
			}

			t.media.style.width = t.width + 'px'
			t.media.style.height = t.container.style.height = t.height + 'px'
		},

		showControls: function() {
			var t = this

			if (t.isControlsVisible) return

			t.controls.style.bottom = 0

			if (t.options.mediaTitle) {
				t.title.style.top = 0
			}

			t.isControlsVisible = true
		},

		hideControls: function() {
			var t = this

			if (!t.isControlsVisible || t.options.alwaysShowControls) return

			t.controls.style.bottom = '-45px'

			t.playbackRateOpts.style.display = 'none'

			if (t.options.mediaTitle) {
				t.title.style.top = '-35px'
			}

			t.isControlsVisible = false
		},

		setControlsTimer: function(timeout) {
			var t = this

			if (t.options.alwaysShowControls) {
				return
			}

			clearTimeout(t.controlsTimer)

			t.controlsTimer = setTimeout(function() {
				t.hideControls()
			}, timeout)
		},

		updateTimeline: function(e) {
			var t = this
			var el = e !== undefined ? e.target : t.media
			var percent = null
			var _W = _css(t.slider, 'width')

			// Support buffered
			if (
				el.buffered &&
				el.buffered.length > 0 &&
				el.buffered.end &&
				el.duration
			) {
				percent = el.buffered.end(el.buffered.length - 1) / el.duration
			}
			// Support bufferedBytes
			else if (
				el.bytesTotal !== undefined &&
				el.bytesTotal > 0 &&
				el.bufferedBytes !== undefined
			) {
				percent = el.bufferedBytes / el.bytesTotal
			}
			// Support progressEvent.lengthComputable
			else if (e && e.lengthComputable && e.total !== 0) {
				percent = e.loaded / e.total
			}

			// Update the timeline
			if (percent !== null) {
				percent = Math.min(1, Math.max(0, percent))
				t.loaded.style.width = _W * percent + 'px'
				// Adjust when pause change from playing (魅族)
				if (t.media.paused) {
					setTimeout(function() {
						t.loaded.style.width = _W * percent + 'px'
						t.updateTimeline()
					}, 300)
				}
			}

			if (t.media.currentTime !== undefined && t.media.duration) {
				// Update bar and handle
				var _w = Math.round(
					(_W * t.media.currentTime) / t.media.duration
				)
				t.current.style.width = _w + 'px'
				t.handle.style.left =
					_w - Math.round(_css(t.handle, 'width') / 2) + 'px'
			}
		},

		updateTime: function() {
			var t = this
			t.currentTime.innerHTML = timeFormat(t.media.currentTime, t.options)

			// Duration is 1 in (读者) device
			if (t.options.duration > 1 || t.media.duration > 1) {
				t.durationDuration.innerHTML = timeFormat(
					t.options.duration > 1
						? t.options.duration
						: t.media.duration,
					t.options
				)
			}
		},

		enterFullScreen: function() {
			var t = this
			// Attempt to do true fullscreen
			if (zyMedia.features.nativeFullscreenPrefix != '-') {
				t.container[
					zyMedia.features.nativeFullscreenPrefix +
						'RequestFullScreen'
				]()
			} else if (zyMedia.features.hasOldNativeFullScreen) {
				t.media.webkitEnterFullscreen()
				return
			}

			// Set it to not show scroll bars so 100% will work
			_addClass(document.documentElement, 'zy_fullscreen')

			// Make full size
			t.media.style.width = t.container.style.width = '100%'
			t.media.style.height = t.container.style.height = '100%'
			// :-webkit-full-screen style not work in app webview, 乐pro3 Android 6.0.1
			t.container.style.zIndex = '1001'
			_addClass(t.fullscreenBtn, 'zy_unfullscreen')
			t.isFullScreen = true
		},

		exitFullScreen: function() {
			var t = this
			// Come out of native fullscreen
			if (isInFullScreenMode() || t.isFullScreen) {
				if (zyMedia.features.nativeFullscreenPrefix != '-') {
					document[
						zyMedia.features.nativeFullscreenPrefix +
							'CancelFullScreen'
					]()
				} else if (zyMedia.features.hasOldNativeFullScreen) {
					document.webkitExitFullscreen()
				}
			}
			_removeClass(document.documentElement, 'zy_fullscreen')
			t.media.style.width = t.width + 'px'
			t.container.style.width = ''
			t.media.style.height = t.container.style.height = t.height + 'px'
			t.container.style.zIndex = ''
			_removeClass(t.fullscreenBtn, 'zy_unfullscreen')
			t.isFullScreen = false
		},

		// Media container
		buildContainer: function() {
			var t = this

			t.container = t.media.parentNode
			t.container.style.overflow = 'hidden'
			// Preset container's height by aspectRation
			t.container.style.height =
				(t.isVideo
					? _css(t.container, 'width') / t.options.aspectRation
					: t.options.audioHeight) + 'px'
			t.container.innerHTML =
				'<div class="zy_wrap"></div><div class="zy_controls"></div>' +
				(t.options.mediaTitle
					? '<div class="zy_title">' + t.options.mediaTitle + '</div>'
					: '')

			t.title = t.container.querySelector('.zy_title')

			t.media.setAttribute('preload', t.options.preload)
			// iOS's playsinline, https://webkit.org/blog/6784/new-video-policies-for-ios/
			if (zyMedia.features.isPlaysInline) {
				t.media.setAttribute('playsinline', '')
			}
			t.container.querySelector('.zy_wrap').appendChild(t.media)
			t.controls = t.container.querySelector('.zy_controls')

			if (t.isVideo) {
				t.width = t.options.videoWidth
				t.height = t.options.videoHeight

				if (t.width == '100%' && t.height == 'auto') {
					t.enableAutoSize = true
				}
				t.setPlayerSize(t.width, t.height)
			}
		},

		// Play/pause button
		buildPlaypause: function() {
			var t = this
			var play = document.createElement('div')
			play.className = 'zy_playpause_btn_play'
			t.controls.appendChild(play)
			play.addEventListener('click', function() {
				t.media.isUserClick = true

				if (t.media.paused) {
					if (typeof t.options.beforePlay === 'function') {
						if (t.options.beforePlay(t.media)) {
							return
						}
					}

					if (t.media.isError) {
						var _currentTime = t.media.currentTime
						// Allow this to play video later
						t.media.load()
						t.media.isError = false
						t.media.currentTime = _currentTime
					}

					t.media.play()

					// Controls bar auto hide after 5s
					if (!t.media.paused) {
						t.setControlsTimer(5000)
					}
				} else {
					t.media.pause()
				}
			})

			function togglePlayPause(s) {
				if (t.media.isUserClick || t.options.autoplay) {
					if ('play' === s) {
						play.className = 'zy_playpause_btn_pause'
					} else {
						play.className = 'zy_playpause_btn_play'
					}
				}
			}

			t.media.addEventListener('play', function() {
				togglePlayPause('play')
			})

			t.media.addEventListener('playing', function() {
				togglePlayPause('play')
			})

			t.media.addEventListener('pause', function() {
				togglePlayPause('pse')
			})

			t.media.addEventListener('paused', function() {
				togglePlayPause('pse')
			})
		},

		// Timeline
		buildTimeline: function() {
			var t = this
			var timeline = document.createElement('div')
			timeline.className = 'zy_timeline'
			timeline.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>'
			t.controls.appendChild(timeline)

			t.slider = timeline.children[0]
			t.buffering = t.slider.children[0]
			t.loaded = t.slider.children[1]
			t.current = t.slider.children[2]
			t.handle = t.slider.children[3]

			var isPointerDown = false
			var _X = t.slider.getBoundingClientRect().left
			var _W = _css(t.slider, 'width')
			var _W_HANDLE_HALF = _css(t.handle, 'width') / 2

			var pointerMove = function(e) {
				e.preventDefault()
				e.stopPropagation()

				var _time = 0
				var x

				if (e.changedTouches) {
					x = e.changedTouches[0].pageX
				} else {
					x = e.pageX
				}

				if (t.media.duration) {
					if (x < _X) {
						x = _X
					} else if (x > _W + _X) {
						x = _W + _X
					}

					// Update handle element position
					t.handle.style.left = x - _W_HANDLE_HALF - _X + 'px'

					_time = ((x - _X) / _W) * t.media.duration
					// Update currentTime element value
					t.currentTime.innerHTML = timeFormat(
						t.media.currentTime,
						t.options
					)

					if (isPointerDown && _time !== t.media.currentTime) {
						t.media.currentTime = _time
					}
				}

				// Do not hide controls when drag timeline
				clearTimeout(t.controlsTimer)
			}
			// Handle clicks
			if (zyMedia.features.hasTouch) {
				timeline.addEventListener('touchstart', function(e) {
					isPointerDown = true
					t.media.pause()
					pointerMove(e)
					_X = t.slider.getBoundingClientRect().left
					_W = _css(t.slider, 'width')
					timeline.addEventListener('touchmove', pointerMove)
					timeline.addEventListener('touchend', function(e) {
						pointerMove(e)
						isPointerDown = false
						t.media.play()
						t.media.isUserClick = true
						t.setControlsTimer(5000)
						timeline.removeEventListener('touchmove', pointerMove)
					})
				})
			} else {
				timeline.addEventListener('mousedown', function(e) {
					isPointerDown = true
					t.media.pause()
					pointerMove(e)
					_X = t.slider.getBoundingClientRect().left
					_W = _css(t.slider, 'width')
					timeline.addEventListener('mousemove', pointerMove)
					timeline.addEventListener('mouseup', function(e) {
						pointerMove(e)
						isPointerDown = false
						t.media.play()
						t.media.isUserClick = true
						t.slider.addEventListener('mousemove', pointerMove)
					})
				})
			}

			//4Hz ~ 66Hz, no longer than 250ms
			t.media.addEventListener('timeupdate', function(e) {
				t.updateTimeline(e)
			})
		},

		// Current time 00:00/00:00
		buildCurrentTime: function() {
			var t = this

			var time = document.createElement('div')
			time.className = 'zy_currenttime'
			time.innerHTML = timeFormat(0, t.options)
			t.controls.appendChild(time)

			t.currentTime = time

			//4Hz ~ 66Hz, no longer than 250ms
			t.media.addEventListener('timeupdate', function() {
				t.updateTime()
			})
		},

		// Duration time 00:00/00:00
		buildTotalTime: function() {
			var t = this

			var time = document.createElement('div')
			time.className = 'zy_time'
			time.innerHTML = timeFormat(t.options.duration, t.options)
			t.controls.appendChild(time)

			t.durationDuration = time
		},

		// Fullscreen button
		buildFullscreen: function() {
			var t = this
			// Native events
			if (zyMedia.features.nativeFullscreenPrefix != '-') {
				// Chrome doesn't alays fire this in an iframe
				var func = function(e) {
					if (t.isFullScreen) {
						if (!isInFullScreenMode()) {
							t.exitFullScreen()
						}
					}
				}

				document.addEventListener(
					zyMedia.features.nativeFullscreenPrefix +
						'fullscreenchange',
					func
				)
			}

			t.fullscreenBtn = document.createElement('div')
			t.fullscreenBtn.className = 'zy_fullscreen_btn'
			t.controls.appendChild(t.fullscreenBtn)

			t.fullscreenBtn.addEventListener('click', function() {
				if (
					(zyMedia.features.nativeFullscreenPrefix != '-' &&
						isInFullScreenMode()) ||
					t.isFullScreen
				) {
					t.exitFullScreen()
				} else {
					t.enterFullScreen()
				}
			})
		},

		// PlaybackRate,set playback speed of media
		buildPlaybackRate: function() {
			var t = this

			t.playbackRateBtn = document.createElement('div')
			t.playbackRateBtn.className = 'zy_playback_rate'
			t.playbackRateBtn.innerHTML =
				'<ul class="zy_playback_rate_option"><li>2</li><li>1.5</li><li class="active">1</li><li>0.75</li><li>0.5</li></ul><div class="zy_playback_rate_val">X1</div>'
			t.controls.appendChild(t.playbackRateBtn)

			t.playbackRateOpts = t.playbackRateBtn.querySelector(
				'.zy_playback_rate_option'
			)
			t.playbackRateVal = document.querySelector('.zy_playback_rate_val')

			t.playbackRateBtn.addEventListener('click', function() {
				if (t.playbackRateOpts.style.display !== 'block') {
					t.playbackRateOpts.style.display = 'block'
				} else {
					t.playbackRateOpts.style.display = 'none'
				}
			})

			t.playbackRateOpts.addEventListener('click', function(e) {
				var el = e.target
				if (el.nodeName === 'LI' && el.className !== 'active') {
					t.playbackRateVal.textContent = 'X' + el.textContent
					t.playbackRateOpts.querySelector('.active').className = ''
					el.className = 'active'
					t.media.playbackRate = el.textContent
				}
			})
		},

		// bigPlay, loading and error info
		buildDec: function() {
			var t = this

			var loading = document.createElement('div')
			loading.className = 'dec_loading'
			loading.style.display = 'none'
			t.container.appendChild(loading)

			var error = document.createElement('div')
			error.className = 'dec_error'
			error.style.display = 'none'
			error.innerHTML = '播放失败,请重试'
			t.container.appendChild(error)

			var bigPlay = document.createElement('div')

			if (!zyMedia.features.isVendorBigPlay) {
				bigPlay.className = 'dec_play'
				t.container.appendChild(bigPlay)
				bigPlay.addEventListener('click', function() {
					// For some device trigger 'play' event
					t.media.isUserClick = true

					if (typeof t.options.beforePlay === 'function') {
						if (t.options.beforePlay(t.media)) {
							return
						}
					}

					if (t.media.isError) {
						var _currentTime = t.media.currentTime
						// Allow this to play video later
						t.media.load()
						t.media.isError = false
						t.media.currentTime = _currentTime
					}

					t.media.play()
					// Controls bar auto hide after 5s
					if (!t.media.paused) {
						t.setControlsTimer(5000)
					}
				})
			}

			t.media.addEventListener('play', function() {
				// Only for user click
				if (t.media.isUserClick) {
					bigPlay.style.display = 'none'
					loading.style.display = ''
					t.buffering.style.display = 'none'
				}
			})

			t.media.addEventListener('playing', function() {
				bigPlay.style.display = 'none'
				loading.style.display = 'none'
				t.buffering.style.display = 'none'
				error.style.display = 'none'

				clearTimeout(t.media._st)
			})

			t.media.addEventListener('seeking', function() {
				loading.style.display = ''
				bigPlay.style.display = 'none'
				t.buffering.style.display = ''

				clearTimeout(t.media._st)
			})

			t.media.addEventListener('seeked', function() {
				loading.style.display = 'none'
				t.buffering.style.display = 'none'
			})

			t.media.addEventListener('pause', function() {
				bigPlay.style.display = ''
				// Hide loading and buffering when paused
				loading.style.display = 'none'
				t.buffering.style.display = 'none'

				clearTimeout(t.media._st)
			})

			t.media.addEventListener('waiting', function() {
				loading.style.display = ''
				bigPlay.style.display = 'none'
				error.style.display = 'none'
				t.buffering.style.display = ''

				// Trigger error if waiting time longer than 30s
				t.media._st = setTimeout(function() {
					var _event = document.createEvent('Event')
					_event.initEvent('error', true, true)
					t.media.dispatchEvent(_event)
				}, 30000)
			})

			// Don't listen to 'loadeddata' and 'canplay',
			// some Android device can't fire 'canplay' or irregular working when use 'createEvent' to trigger 'canplay' (读者i800)

			// Error handling
			t.media.addEventListener('error', function(e) {
				loading.style.display = 'none'
				bigPlay.style.display = ''
				t.buffering.style.display = 'none'
				t.media.pause()
				error.style.display = ''

				// For load method when replay
				t.media.isError = true

				if (typeof t.options.error == 'function') {
					t.options.error(e)
				}
			})
		},

		init: function() {
			var t = this

			// Build
			var batch = [
				'Container',
				'Playpause',
				'CurrentTime',
				'Timeline',
				'TotalTime'
			]
			if (t.options.enableFullscreen && t.isVideo) {
				batch.push('Fullscreen')
			}

			if (t.isVideo) {
				batch.push('Dec')
			}

			if (t.isVideo && t.options.showPlaybackRate) {
				batch.push('PlaybackRate')
			}

			for (var i = 0; i < batch.length; i++) {
				try {
					t['build' + batch[i]]()
				} catch (exp) {}
			}

			// Controls fade
			if (t.isVideo) {
				if (zyMedia.features.hasTouch) {
					t.media.addEventListener('touchend', function() {
						// Toggle controls
						if (t.isControlsVisible) {
							t.hideControls()
						} else {
							t.showControls()
							// Controls bar auto hide after 5s
							if (!t.media.paused) {
								t.setControlsTimer(5000)
							}
						}
					})
				} else {
					// Click to play/pause
					t.media.addEventListener('click', function() {
						if (t.media.paused) {
							t.media.play()
						} else {
							t.media.pause()
						}
					})

					// Show/hide controls
					t.container.addEventListener('mouseenter', function() {
						t.showControls()
						t.setControlsTimer(5000)
					})

					t.container.addEventListener('mousemove', function() {
						t.showControls()
						t.setControlsTimer(5000)
					})
				}

				if (t.options.hideVideoControlsOnLoad) {
					t.hideControls()
				}

				t.media.addEventListener('loadedmetadata', function(e) {
					if (t.enableAutoSize) {
						// For more properly videoWidth or videoHeight of HM 1SW(小米), QQ browser is 0
						setTimeout(function() {
							if (!isNaN(t.media.videoHeight)) {
								t.setPlayerSize()
							}
						}, 50)
					}
				})
			}

			t.media.addEventListener('play', function() {
				var p

				for (var i in zyMedia.players) {
					p = zyMedia.players[i]

					if (
						p.id != t.id &&
						t.options.pauseOtherPlayers &&
						!p.paused &&
						!p.ended
					) {
						try {
							p.media.pause()
						} catch (exp) {}
					}
				}
			})

			// Pause all media when page's visibilityState is hidden
			if (t.options.enableVisibilityState && zyMedia.features.vChange) {
				document.addEventListener(zyMedia.features.vChange, function() {
					if (document[zyMedia.features.vState] == 'hidden') {
						// 100ms time for switching between app's webviews
						setTimeout(function() {
							;[].forEach.call(
								document.querySelectorAll('video, audio'),
								function(el) {
									el.pause()
								}
							)
						}, 100)
					}
				})

				// Only one times for binding zyMedia.features.vChange
				zyMedia.features.vChange = ''
			}

			// Adjust controls when orientation change, 500ms for Sumsung tablet
			window.addEventListener('orientationchange', function() {
				if (t.isVideo) {
					setTimeout(function() {
						t.setPlayerSize()
					}, 500)
				}
			})

			t.media.addEventListener('ended', function(e) {
				t.media.currentTime = 0

				if (t.options.autoLoop) {
					t.media.play()
				} else {
					if (t.isVideo) {
						setTimeout(function() {
							// Fixing an Android stock browser bug, where "seeked" isn't fired correctly after ending the video and jumping to the beginning
							t.container.querySelector(
								'.dec_loading'
							).style.display = 'none'
							// Show big play button after "ended" -> "paused" -> "seeking" -> "seeked"
							t.container.querySelector(
								'.dec_play'
							).style.display = ''
						}, 20)
					}

					if (t.options.showPosterAfterEnd) {
						t.media.load()
					} else {
						t.media.pause()
					}
				}

				t.updateTimeline(e)
			})

			t.media.addEventListener('loadedmetadata', function(e) {
				t.updateTime()
			})

			if (t.options.autoplay) {
				t.media.isUserClick = false
				t.media.play()
			}

			if (typeof t.options.success == 'function') {
				t.options.success(t.media)
			}
		}
	}

	// String or node
	window.zymedia = function(selector, options) {
		if (typeof selector === 'string') {
			;[].forEach.call(document.querySelectorAll(selector), function(el) {
				new zyMedia.MediaPlayer(el, options)
			})
		} else {
			new zyMedia.MediaPlayer(selector, options)
		}
	}
})()

③ index.html

<div class="zy_media">
    <video poster="test.jpg" data-config='{"mediaTitle": "《疯狂动物城》--腾讯视频"}'>
        <source src="test.mp4" type="video/mp4">
        您的浏览器不支持HTML5视频
    </video>
</div>

④ index.js

zymedia('video');
    // zymedia('video', {...参数});

五、其他常见插件

① superslide,http://www.superslide2.com/
② iscroll,https//github.com/cubiq/iscroll

插件使用总结:
① 确认插件实现的功能;
② 去官网上查看使用说明;
③ 下载插件;
④ 打开 demo 实例文件,查看需要引入的相关文件,并且引入;
⑤ 复制 demo 实例文件中的 html 结构、css 样式及 js 代码。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

栈老师不回家

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

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

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

打赏作者

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

抵扣说明:

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

余额充值