移动端之轮播图

功能

  • 自动播放轮播图
  • 手指拖动播放轮播图

步骤
1.利用定时器自动播放图片

2.等过渡完成之后 再去判断 监听过渡完成的事件

3.去掉ol下的li的current类 并为当前li添加current类

4.手指滑动轮播图

  • 触摸元素touchstart:获取手指初始坐标。 手指触摸时 停止定时器
  • 移动手指touchmove:计算手指的滑动距离 并且移动盒子
  • 手指离开 根据距离去判断播放上一张与下一张
  • 如果移动距离小于50px 则回弹
  • 手指离开时 取消定时器

html文件

  <!-- focus 焦点图 --><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 class="circle"><li class="current"></li><li></li><li></li></ol></div>

css文件

.focus {position: relative;overflow: hidden;margin-top: 44px;}.focus ul {overflow: hidden;width: 500%;margin-left: -100%;margin-block-start: 0em;margin-block-end: 0em;padding-inline-start: 0px;
}.focus ul li {float: left;width: 20%;
}.focus img {width: 100%;
}.circle {position: absolute;bottom: 20px;right: 20px;
}.circle li {display: inline-block;width: 5px;height: 5px;background-color: red;transition: all 0.2s;}li.current {width: 10px;background-color: #fff;
}

js文件

window.addEventListener('load', function () {//获取元素let focus = document.querySelector('.focus');let ul = focus.children[0];let ol = focus.children[1];let focusWidth = focus.offsetWidth;//1.利用定时器自动播放图片let index = 0;let timer = setInterval(() => {index++;let translatex = -index * focusWidth;ul.style.transition = 'all 0.5s'ul.style.transform = 'translateX(' + translatex + 'px)'}, 2000)//2.等过渡完成之后 再去判断  监听过渡完成的事件ul.addEventListener('transitionend', function () {if (index >= 3) {index = 0;let translatex = -index * focusWidth;ul.style.transition = 'none';ul.style.transform = 'translateX(' + translatex + 'px)'} else if (index < 0) {index = 2;let translatex = -index * focusWidth;ul.style.transition = 'none';ul.style.transform = 'translateX(' + translatex + 'px)'}//3.去掉ol下的li的current类 并为当前li添加current类ol.querySelector('.current').classList.remove('current');ol.children[index].classList.add('current');})//4.手指滑动轮播图// 触摸元素touchstart:获取手指初始坐标let starX = 0;let moveX = 0;let flag = false;ul.addEventListener('touchstart', function (e) {starX = e.targetTouches[0].pageX;//手指触摸时 停止定时器clearTimeout(timer)})//移动手指touchmove:计算手指的滑动距离 并且移动盒子ul.addEventListener('touchmove', function (e) {//计算移动距离moveX = e.targetTouches[0].pageX - starX;// 移动盒子:盒子原来的距离+手指移动的距离let translatex = -index * focusWidth + moveX;//手指移动的时候 不需要动画效果  所以取消过渡ul.style.transition = 'none';ul.style.transform = 'translateX(' + translatex + 'px)';//阻止屏幕滚动的默认事件flag = true;e.preventDefault()})//手指离开  根据距离去判断播放上一张与下一张ul.addEventListener('touchend', function (e) {if (flag) {//如果移动距离大于50像素 播放上一张或者下一张if (Math.abs(moveX) > 50) {//如果是正值  就播放上一张if (moveX > 0) {index--} else {//如果是负值 就播放下一张index++}let translatex = -index * focusWidth;ul.style.transition = 'all 0.3s';ul.style.transform = 'translateX(' + translatex + 'px)'}else {//如果移动距离小于50px 则回弹let translatex = -index * focusWidth;ul.style.transition = 'all .1s';ul.style.transform = 'translateX(' + translatex + 'px)';}}//手指离开时 取消定时器clearInterval(timer);timer = setInterval(function () {index++;let translatex = -index * focusWidth;ul.style.transition = 'all 0.5s'ul.style.transform = 'translateX(' + translatex + 'px)'},2000)})})

classList属性

classList属性是HTML新增的属性 能返回元素的类名

添加类

  • element.classList.add(’类名’);

移除类

  • element.classList.remove(’类名’);

切换类

  • element.classList.toggle(’类名’);

<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>classList属性</title><style>* {margin: 0;padding: 0;}.bg_color {background-color: #000;}</style>
</head>
<body><div class="one two box"></div><button>按钮</button>
</body>
<script>let box  = document.querySelector('div');let bth = document.querySelector('button');let body = document.bodybox.classList.add('three');box.classList.remove('box');bth.addEventListener('click',function () {body.classList.toggle('bg_color')})</script>
</html>

移动端之click事件延时方案

禁用缩放

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

封装touch事件


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) {callback && callback(); // 执行回调函数}isMove = false;  //  取反 重置startTime = 0;});
}
//调用tap(div, function(){   // 执行代码  });

fastclick插件

使用
1.引入 js 插件文件。

2.按照规定语法使用。

3.fastclick 插件解决 300ms 延迟。

;
(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.bindfunction 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 requiredif (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 framescase '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 inputsreturn !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 trackedclickEvent = 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 eventif (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 trackingif (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 attributeif (labelElement.control !== undefined) {return labelElement.control;}// All browsers under test that support touch events also support the HTML5 htmlFor attributeif (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-labelreturn 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 nulltargetElement = 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 eventif (!this.targetElement) {return true;}if (event.forwardedTouchEvent) {return true;}// Programmatically generated events targeting a specific element should be permittedif (!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 eventevent.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 FastClickif (typeof window.ontouchstart === 'undefined') {return true;}// Chrome version - zero for other browserschromeVersion = +(/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 FastClickif (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/251if (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 browsersfirefoxVersion = +(/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=922896metaViewport = 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.aspxif (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

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

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

注意:swiper中的类名不可随便更改

Swiper的使用方法

官网:swiper的使用

swiper之轮播图

<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><title>Swiper之轮播图</title><meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"><!-- Link Swiper's CSS --><link rel="stylesheet" href="./swiper-master/package/swiper-bundle.min.css"><!-- Demo styles --><style>html,body {position: relative;height: 100%;}body {background: #eee;font-family: Helvetica Neue, Helvetica, Arial, sans-serif;font-size: 14px;color: #000;margin: 0;padding: 0;}.swiper-container {width: 800px;}img {width: 800px;}.swiper-slide {text-align: center;font-size: 18px;background: #fff;/* Center slide text vertically */display: -webkit-box;display: -ms-flexbox;display: -webkit-flex;display: flex;-webkit-box-pack: center;-ms-flex-pack: center;-webkit-justify-content: center;justify-content: center;-webkit-box-align: center;-ms-flex-align: center;-webkit-align-items: center;align-items: center;}</style>
</head><body>
<!-- Swiper -->
<div class="swiper-container"><div class="swiper-wrapper"><div class="swiper-slide"><img src="./image/desktop.jpg" alt=""></div><div class="swiper-slide"><img src="./image/iso.jpg" alt=""></div><div class="swiper-slide"><img src="./image/MI.jpg" alt=""></div><div class="swiper-slide"><img src="./image/iso.jpg" alt=""></div></div><!-- Add Pagination --><div class="swiper-pagination"></div><!-- Add Arrows --><div class="swiper-button-next"></div><div class="swiper-button-prev"></div>
</div><!-- Swiper JS -->
<script src="./swiper-master/package/swiper-bundle.min.js"></script><!-- Initialize Swiper -->
<script>var swiper = new Swiper('.swiper-container', {spaceBetween: 30,centeredSlides: true,autoplay: {delay: 2500,disableOnInteraction: false,},pagination: {el: '.swiper-pagination',clickable: true,},navigation: {nextEl: '.swiper-button-next',prevEl: '.swiper-button-prev',},});
</script>
</body></html>

SuperSlider

SuperSlider之tab栏切换

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Language" content="zh-CN">
<meta name="Keywords" content="SuperSlide,jQuery标签切换效果,Tab切换效果">
<meta name="Description" content="SuperSlide 致力于解决网站大部分特效展示问题,使网站代码规范整洁,方便维护更新。网站上常用的“焦点图/幻灯片”、“Tab标签切换”、“图片滚动”、“无缝滚动”等等只需要一个SuperSlide即可解决!还可以多个SuperSlide组合创造更多效果">
<title>SuperSlide - Tab切换效果</title>
<script type="text/javascript" src="../jquery1.42.min.js"></script><script type="text/javascript" src="../jquery.SuperSlide.2.1.3.js"></script>
</head><body><style type="text/css">/* css 重置 */*{margin:0; padding:0; list-style:none; }body{ background:#fff; font:normal 12px/22px 宋体;  }img{ border:0;  }a{ text-decoration:none; color:#333;  }a:hover{ color:#1974A1;  }/* 本例子css */.slideTxtBox{ width:450px; border:1px solid #ddd; text-align:left;  }.slideTxtBox .hd{ height:30px; line-height:30px; background:#f4f4f4; padding:0 10px 0 20px;   border-bottom:1px solid #ddd;  position:relative; }.slideTxtBox .hd ul{ float:left;  position:absolute; left:20px; top:-1px; height:32px;   }.slideTxtBox .hd ul li{ float:left; padding:0 15px; cursor:pointer;  }.slideTxtBox .hd ul li.on{ height:30px;  background:#fff; border:1px solid #ddd; border-bottom:2px solid #fff; }.slideTxtBox .bd ul{ padding:15px;  zoom:1;  }.slideTxtBox .bd li{ height:24px; line-height:24px;   }.slideTxtBox .bd li .date{ float:right; color:#999;  }/* 下面是前/后按钮代码,如果不需要删除即可 */.slideTxtBox .arrow{  position:absolute; right:10px; top:0; }.slideTxtBox .arrow a{ display:block;  width:5px; height:9px; float:right; margin-right:5px; margin-top:10px;  overflow:hidden;cursor:pointer; background:url("../images/arrow.png") 0 0 no-repeat; }.slideTxtBox .arrow .next{ background-position:0 -50px;  }.slideTxtBox .arrow .prevStop{ background-position:-60px 0; }.slideTxtBox .arrow .nextStop{ background-position:-60px -50px; }</style><div class="slideTxtBox"><div class="hd"><!-- 下面是前/后按钮代码,如果不需要删除即可 --><span class="arrow"><a class="next"></a><a class="prev"></a></span><ul><li>教育</li><li>培训</li><li>出国</li></ul></div><div class="bd"><ul><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">中国打破了世界软件巨头规则</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">口语:会说中文就能说英语!</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">农场摘菜不如在线学外语好玩</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">数理化老师竟也看学习资料?</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">学英语送ipad2,45天突破听说</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">学外语,上北外!</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">那些无法理解的荒唐事</a></li></ul><ul><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">名师教作文:3妙招巧写高分</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">耶鲁小子:教你备考SAT</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">施强:高端专业语言教学</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">数理化老师竟也看学习资料?</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">【推荐】名校英语方法曝光!</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">2012高考“考点”大曝光!!</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">涨价仍爆棚假日旅游冰火两重天</a></li></ul><ul><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">澳大利亚八大名校招生说明会</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">2012世界大学排名新鲜出炉</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">新加坡留学,国际双语课程</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">高考后留学日本名校随你选</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">教育培训行业优势资源推介</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">即刻预约今年最后一场教育展</a></li><li><span class="date">2011-11-11</span><a href="http://www.SuperSlide2.com" target="_blank">女友坚持警局完婚不抛弃</a></li></ul></div></div><script type="text/javascript">jQuery(".slideTxtBox").slide();</script></body>
</html>
<script type="text/javascript">var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fa630f96b6a9dd549675d26373853f7f1' type='text/javascript'%3E%3C/script%3E"));
</script>

zy.media.js

githup地址:zy.media.js

主要时为解决视频在各个浏览器显示不一致的问题

<!DOCTYPE html>
<html><head><meta charset="utf-8" /><metaname="viewport"content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"/><title>掌阅--媒体播放器</title><style>.zy_media {width: 600px;height: 600px;margin: 200px auto;}</style><link rel="stylesheet" href="zy.media.min.css" /></head><body><div class="zy_media"><video poster="test.jpg" data-config='{"mediaTitle": "《疯狂动物城》--腾讯视频"}'><source src="test.mp4" type="video/mp4" />您的浏览器不支持HTML5视频</video></div><script src="../src/zy.media.js"></script><script>zymedia('video')</script></body>
</html>

移动端框架

框架:顾名思义是一套架构 拥有完整的网页解决方案

框架:大而全 一整套解决方案

插件:小而全 某个功能的解决方案

bootstrap之轮播图

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>bootstrap之轮播图</title><!-- 引进bootstrap css文件 --><link rel="stylesheet" href="./bootstrap/css/bootstrap.min.css"><!-- 引进jquery --><script src="./bootstrap/js/jquery-3.6.0.js"></script><!--引进bootstrap js文件 --><script src="./bootstrap/js/bootstrap.min.js"></script><style>.focus {width: 800px;height: 600px;margin: 200px auto;}</style>
</head><body><div class="focus"><div id="carousel-example-generic" class="carousel slide" data-ride="carousel"><!-- Indicators --><ol class="carousel-indicators"><li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li><li data-target="#carousel-example-generic" data-slide-to="1"></li><li data-target="#carousel-example-generic" data-slide-to="2"></li></ol><!-- Wrapper for slides --><div class="carousel-inner" role="listbox"><div class="item active"><img src="./image/desktop.jpg" alt="..."><div class="carousel-caption"></div></div><div class="item"><img src="./image/iso.jpg" alt="..."><div class="carousel-caption"></div></div><div class="item"><img src="./image/MI.jpg" alt="..."><div class="carousel-caption"></div></div></div><!-- Controls --><a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"><span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span><span class="sr-only">Previous</span></a><a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span><span class="sr-only">Next</span></a></div></div>
</body>
<script>$('.carousel').carousel({interval: 2000})
</script></html>

本地存储

为满足需求,会经常性在本地存储大量的数据,HTML5规范提出了相关解决方案。

本地存储特性

  • 数据存储在用户浏览器中

  • 设置、读取方便、甚至页面刷新不丢失数据

  • 容量较大,sessionStorage约5M、localStorage约20M

  • 只能存储字符串-

window.sessionStorage

1、生命周期为关闭浏览器窗口

2、在同一个窗口(页面)下数据可以共享

3、以键值对的形式存储使用

存储数据:

sessionStorage.setItem(key, value)

获取数据

sessionStorage.getItem(key)

删除数据:

sessionStorage.removeItem(key)

清空数据:(所有都清除掉)

sessionStorage.clear()

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>本地存储</title>
</head><body><input type="text"><button class="set">存储数据</button><button class="get">设置数据</button><button class="remove">删除数据</button><button class="del">清空所有数据</button></body>
<script>// 获取元素var ipt = document.querySelector('input');var set = document.querySelector('.set');var get = document.querySelector('.get');var remove = document.querySelector('.remove');var del = document.querySelector('.del');// 存储数据set.addEventListener('click', function() {//当我们点击之后,就把表单里面的值存储起来var val = ipt.value;sessionStorage.setItem('uname', val);})//获取数据get.addEventListener('click', function() {console.log(sessionStorage.getItem('uname'))})// 删除数据remove.addEventListener('click', function() {console.log(sessionStorage.removeItem('uname'))})//清空数据del.addEventListener('click', function() {console.log(sessionStorage.clear())})
</script></html>

window.localStorage

1、声明周期永久生效,除非手动删除 否则关闭页面也会存在

2、可以多窗口(页面)共享(同一浏览器可以共享)

以键值对的形式存储使用

存储数据:

localStorage.setItem(key, value)

获取数据:

localStorage.getItem(key)

删除数据:

localStorage.removeItem(key)

清空数据:(所有都清除掉)

localStorage.clear()

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>window.localStorage</title>
</head><body><input type="text"><button class="set">存储数据</button><button class="get">获取数据</button><button class="remove">移除数据</button><button class="del">删除数据</button>
</body>
<script>// 获取数据let ipt = document.querySelector('input');let set = document.querySelector('.set');let get = document.querySelector('.get');let remove = document.querySelector('.remove');let del = document.querySelector('.del')//设置数据set.addEventListener('click', function() {let val = ipt.value;window.localStorage.setItem('uname', val);})// 获取数据set.addEventListener('click', function() {window.localStorage.getItem('uname');})// 移除数据remove.addEventListener('click', function() {window.localStorage.removeItem('uname')});//删除数据del.addEventListener('click', function() {window.localStorage.clear()})
</script></html>

记住用户名

如果勾选记住用户名, 下次用户打开浏览器,就在文本框里面自动显示上次登录的用户名

案例分析

  • 把数据存起来,用到本地存储
  • 关闭页面,也可以显示用户名,所以用到localStorage
  • 打开页面,先判断是否有这个用户名,如果有,就在表单里面显示用户名,并且勾选复选框
  • 当复选框发生改变的时候change事件
  • 如果勾选,就存储,否则就移除
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>记住用户名</title>
</head><body><input type="text" id="username"><input type="checkbox" id="remeber">记住用户名</body>
<script>let username = document.querySelector('#username');let rember = document.querySelector('#remeber');if (localStorage.getItem('username')) {username.value = localStorage.getItem('username');rember.checked = true;}rember.addEventListener('change', function(params) {if (this.checked) {localStorage.setItem('username', username.value)} else {localStorage.removeItem('username')}})
</script></html>

Web APIs(七)相关推荐

  1. 2021-09-02 Day17-JS-第七天 Web APIs和DOM

    一.Web APIs 1.Web APIs 和 JS 的关联 1.1 JS的组成 1.2 JS 基础阶段以及 Web APIs 阶段 JS基础阶段: ECMAScript 标准规定的基本语法 基础语法 ...

  2. JavaScript核心Web APIs

    目录 一.Web APIs简介 1 Web APIs和JS基础的关联性 2 MDN详细API 网址 二.DOM 1 什么是DOM 1.1 DOM树 2 获取页面元素 2.1 根据ID获取 2.2 根据 ...

  3. Web APIs 正则表达式综合案例丨小兔仙儿登录页面

    目录 综合案例:小兔鲜登录页面 案例代码:CSS丨common 案例代码:CSS丨index 案例代码:CSS丨login 案例代码:CSS丨register 案例代码:HTML丨index 案例代码 ...

  4. Web APIs三、DOM事件进阶

    零.文章目录 Web APIs三.DOM事件进阶 1.事件流 (1)事件流和两个阶段说明 事件流指的是事件完整执行过程中的流动路径 假设页面里有个div,当触发事件时,会经历两个阶段,分别是捕获阶段. ...

  5. 小白JavaScript学习笔记----web APIs

    目录 web API 操作DOM BOM,比如控制网页元素交互等各种网页交互效果 一.web APIs第一天(DOM-获取元素) 1.1变量声明 1.2Web API 基本认知 1.2.1作用和分类 ...

  6. RESTful  Web APIs设计风格

    RESTful  Web APIs设计风格 RESTful(Representational State Transfer,简称REST)是一种网络Web程序的设计风格和开发方式. 一.RESTful ...

  7. JavaScript(五)—— Web APIs 简介/JavaScript 必须掌握的 DOM 操作 (丰富案例 + 思维导图)

    本篇为 JavaScript 系列笔记第五篇,将陆续更新后续内容.参考:黑马程序员JavaScript核心教程,前端基础教程 系列笔记: JavaScript(一)-- 初识JavaScript / ...

  8. Web APIs 简介

    Web APIs 简介 1 Web APIs 和 JS 基础关联性 1.1 JS 的组成 1.2 JS 基础阶段以及 Web APIs 阶段 JS 基础阶段 我们学习的是 ECMAScript 标准规 ...

  9. JavaScript——Web APIs

    JS的组成 JavaScript由ECMAScript(JavaScript基础).DOM和BOM(Web APIs)组成. 其中,JavaScript基础是ECMAScript标准规定的基本语法:而 ...

最新文章

  1. Microbiome:animalcules-交互式微生物组分析和可视化的R包
  2. java 获取sqlsession_获取Java的MyBatis框架项目中的SqlSession的方法
  3. 4 form j1 w 如何填写_设计必备方法,如何通过数据优化设计?
  4. 如何在Qt Creator中导入图标资源
  5. Atitit.gui api自动化调用技术原理与实践
  6. C# 代码创建mysql存储过程(使用mysqlScript)
  7. 添加mysql.h头文件
  8. 基于Android Studio和Gradle 的小米便签配置和安装
  9. (毕业设计资料)基于单片机万用表量程手动自动电阻电流电压设计
  10. Footprint:如何寻找有增长潜力的NFT项目?
  11. 使用Docker安装Redis并设置自启动
  12. win10 win11黑屏引导转圈开机时间过长
  13. Linux的开源操作系统
  14. 普通用户与root用户的相互切换
  15. vue2中provide/inject的使用和响应式传值
  16. Discuz x2 数据字典
  17. math_角函数反三角函数诱导公式三角/反三角恒等式
  18. Linux 【网络】C10K 和 C1000K 回顾
  19. ITU BT 601建议及与ITU BT656 的区别
  20. 51单片机——矩阵按键逐行扫描短按长按一直按方案1.2

热门文章

  1. 李宏毅深度学习|Datawhale-7月 Task06 卷积神经网络
  2. 乐高于上海月星环球港举办新春互动活动
  3. Kobe -吃鸡版接小球游戏
  4. 挂载google 云端硬盘
  5. Rockchip Android平台查看系统运行帧率的方法
  6. matlab 图像归一化!!
  7. Mapreduce编程模型(一)
  8. mysql高级知识(linux安装mysql+索引+视图+存储过程和函数+触发器)
  9. 网站安全隔离-RBI技术
  10. es5 vs es6 继承