当前位置: 代码迷 >> 综合 >> 【07】JavaScript:13-触屏事件、移动端特效、classList属性、click延时解决方案、移动端开发插件、移动端开发框架、本地存储、Swiper、zy.media、Bootstrap
  详细解决方案

【07】JavaScript:13-触屏事件、移动端特效、classList属性、click延时解决方案、移动端开发插件、移动端开发框架、本地存储、Swiper、zy.media、Bootstrap

热度:41   发布时间:2023-12-22 10:47:58.0

文章目录

  • day07 - Web APIs
    • 1.1. 触屏事件
      • 1.1.1 触屏事件概述
      • 1.1.2 触摸事件对象(TouchEvent)
      • 1.1.3 移动端拖动元素
    • 1.2. 移动端常见特效
      • 1.2.1 案例: 移动轮播图
      • 1.2.2. 案例分析:
    • 1.2.3 classList 属性
      • 1.2.4. 案例分析
      • 1.3.1. 案例:返回顶部
      • 1.3.2.案例分析
    • 1.4. click 延时解决方案
    • 1.5. 移动端常用开发插件
      • 1.5.1. 什么是插件
      • 1.5.2. 插件的使用
      • 1.5.3. Swiper 插件的使用
      • 1.5.4. 其他移动端常见插件
      • 1.5.5. 插件的使用总结
      • 1.5.6. 移动端视频插件 zy.media.js
    • 1.6. 移动端常用开发框架
      • 1.6.1. 移动端视频插件 zy.media.js
      • 1.6.2. Bootstrap
    • 1.7. 本地存储
      • 1.7.1.本地存储特性
      • 1.7.2.window.sessionStorage
      • 1.7.3.window.localStorage
      • 1.7.4.案例:记住用户名
        • 案例分析
    • 1.8. 每日作业-Web APIs第07天
      • 1 - 移动端轮播图
      • 2 - 返回顶部案例
      • 3 - 插件轮播图
      • 4 - 记住用户名
    • 1.9. 随堂测验

day07 - Web APIs

学习目标:

能够写出移动端触屏事件
能够写出常见的移动端特效
能够使用移动端开发插件开发移动端特效
能够使用移动端开发框架开发移动端特效
能够写出 sessionStorage 数据的存储以及获取
能够写出 localStorage 数据的存储以及获取
能够说出它们两者的区别

1.1. 触屏事件

1.1.1 触屏事件概述

移动端浏览器兼容性较好,我们不需要考虑以前 JS 的兼容性问题,可以放心的使用原生 JS 书写效果,但是移动端也有自己独特的地方。比如触屏事件 touch(也称触摸事件),Android 和 IOS 都有。touch 对象代表一个触摸点。触摸点可能是一根手指,也可能是一根触摸笔。触屏事件可响应用户手指(或触控笔)对屏幕或者触控板操作。

常见的触屏事件如下:

(img-ZA50wVLa-1591845376332)(images\图片1.png)]

1.1.2 触摸事件对象(TouchEvent)

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

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

触摸事件对象重点我们看三个常见对象列表:

(img-OlNmTOQd-1591845376334)(images\图片2.png)]

因为平时我们都是给元素注册触摸事件,所以重点记住 targetTocuhes

1.1.3 移动端拖动元素

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

拖动元素三步曲:

(1) 触摸元素 touchstart: 获取手指初始坐标,同时获得盒子原来的位置

(2) 移动手指 touchmove: 计算手指的滑动距离,并且移动盒子

(3) 离开手指 touchend:

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

1.2. 移动端常见特效

1.2.1 案例: 移动轮播图

移动端轮播图功能和基本PC端一致。

  1. 可以自动播放图片
  2. 手指可以拖动播放轮播图

1.2.2. 案例分析:

  1. 自动播放功能

  2. 开启定时器

  3. 移动端移动,可以使用translate 移动

  4. 想要图片优雅的移动,请添加过渡效果
    (img-92a3Ys2q-1591845376337)(images\1551795152(1)].jpg)

  5. 自动播放功能-无缝滚动

  6. 注意,我们判断条件是要等到图片滚动完毕再去判断,就是过渡完成后判断

  7. 此时需要添加检测过渡完成事件 transitionend

  8. 判断条件:如果索引号等于 3 说明走到最后一张图片,此时 索引号要复原为 0

  9. 此时图片,去掉过渡效果,然后移动

  10. 如果索引号小于0, 说明是倒着走, 索引号等于2

  11. 此时图片,去掉过渡效果,然后移动

(img-0z2VkflJ-1591845376343)(images\1551795483(1)].jpg)

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no"><meta http-equiv="X-UA-Compatible" content="ie=edge"><link rel="stylesheet" href="css/normalize.css"><link rel="stylesheet" href="css/index.css"><title>携程在手,说走就走</title><script src="js/index.js"></script>
</head><body><!-- 返回顶部模块 --><div class="goBack"></div><!-- 顶部搜索 --><div class="search-index"><div class="search">搜索:目的地/酒店/景点/航班号</div><a href="#" class="user">我 的</a></div><!-- 焦点图模块 --><div class="focus"><ul><li><img src="upload/focus3.jpg" alt=""></li><li><img src="upload/focus1.jpg" alt=""></li><li><img src="upload/focus2.jpg" alt=""></li><li><img src="upload/focus3.jpg" alt=""></li><li><img src="upload/focus1.jpg" alt=""></li></ul><!-- 小圆点 --><ol><li class="current"></li><li></li><li></li></ol></div><!-- 局部导航栏 --><ul class="local-nav"><li><a href="#" title="景点·玩乐"><span class="local-nav-icon-icon1"></span><span>景点·玩乐</span></a></li><li><a href="#" title="景点·玩乐"><span class="local-nav-icon-icon2"></span><span>景点·玩乐</span></a></li><li><a href="#" title="景点·玩乐"><span class="local-nav-icon-icon3"></span><span>景点·玩乐</span></a></li><li><a href="#" title="景点·玩乐"><span class="local-nav-icon-icon4"></span><span>景点·玩乐</span></a></li><li><a href="#" title="景点·玩乐"><span class="local-nav-icon-icon5"></span><span>景点·玩乐</span></a></li></ul><!-- 主导航栏 --><nav><div class="nav-common"><div class="nav-items"><a href="#">海外酒店</a></div><div class="nav-items"><a href="#">海外酒店</a><a href="#">特价酒店</a></div><div class="nav-items"><a href="#">海外酒店</a><a href="#">特价酒店</a></div></div><div class="nav-common"><div class="nav-items"><a href="#">海外酒店</a></div><div class="nav-items"><a href="#">海外酒店</a><a href="#">特价酒店</a></div><div class="nav-items"><a href="#">海外酒店</a><a href="#">特价酒店</a></div></div><div class="nav-common"><div class="nav-items"><a href="#">海外酒店</a></div><div class="nav-items"><a href="#">海外酒店</a><a href="#">特价酒店</a></div><div class="nav-items"><a href="#">海外酒店</a><a href="#">特价酒店</a></div></div></nav><!-- 侧导航栏 --><ul class="subnav-entry"><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li><li><a href="#"><span class="subnav-entry-icon"></span><span>电话费</span></a></li></ul><!-- 销售模块 --><div class="sales-box"><div class="sales-hd"><h2>热门活动</h2><a href="#" class="more">获取更多福利</a></div><div class="sales-bd"><div class="row"><a href="#"><img src="upload/pic1.jpg" alt=""></a><a href="#"><img src="upload/pic2.jpg" alt=""></a></div><div class="row"><a href="#"><img src="upload/pic3.jpg" alt=""></a><a href="#"><img src="upload/pic4.jpg" alt=""></a></div><div class="row"><a href="#"><img src="upload/pic5.jpg" alt=""></a><a href="#"><img src="upload/pic6.jpg" alt=""></a></div></div></div>
</body></html>
body {
    max-width: 540px;min-width: 320px;margin: 0 auto;font: normal 14px/1.5 Tahoma, "Lucida Grande", Verdana, "Microsoft Yahei", STXihei, hei;color: #000;background: #f2f2f2;overflow-x: hidden;-webkit-tap-highlight-color: transparent;
}ul {
    list-style: none;margin: 0;padding: 0;
}a {
    text-decoration: none;color: #222;
}div {
    box-sizing: border-box;
}/* 搜索模块 */.search-index {
    display: flex;/* 固定定位跟父级没有关系 它以屏幕为准 */position: fixed;top: 0;left: 50%;z-index: 999;/* 固定的盒子应该有宽度 */-webkit-transform: translateX(-50%);transform: translateX(-50%);width: 100%;min-width: 320px;max-width: 540px;height: 44px;/* background-color: pink; */background-color: #F6F6F6;border-top: 1px solid #ccc;border-bottom: 1px solid #ccc;
}.search {
    position: relative;height: 26px;line-height: 24px;border: 1px solid #ccc;flex: 1;font-size: 12px;color: #666;margin: 7px 10px;padding-left: 25px;border-radius: 5px;box-shadow: 0 2px 4px rgba(0, 0, 0, .2);
}.search::before {
    content: "";position: absolute;top: 5px;left: 5px;width: 15px;height: 15px;background: url(../images/sprite.png) no-repeat -59px -279px;background-size: 104px auto;
}.user {
    width: 44px;height: 44px;/* background-color: purple; */font-size: 12px;text-align: center;color: #2eaae0;
}.user::before {
    content: "";display: block;width: 23px;height: 23px;background: url(../images/sprite.png) no-repeat -59px -194px;background-size: 104px auto;margin: 4px auto -2px;
}/* goBack */.goBack {
    display: none;position: fixed;bottom: 50px;right: 20px;width: 38px;height: 38px;background: url(../images/back.png) no-repeat;background-size: 38px 38px;
}/* focus */.focus {
    position: relative;padding-top: 44px;overflow: hidden;
}.focus img {
    width: 100%;
}.focus ul {
    overflow: hidden;width: 500%;margin-left: -100%;
}.focus ul li {
    float: left;width: 20%;
}.focus ol {
    position: absolute;bottom: 5px;right: 5px;margin: 0;
}.focus ol li {
    display: inline-block;width: 5px;height: 5px;background-color: #fff;list-style: none;border-radius: 2px;transition: all .3s;
}.focus ol li.current {
    width: 15px;
}/* local-nav */.local-nav {
    display: flex;height: 64px;margin: 3px 4px;background-color: #fff;border-radius: 8px;
}.local-nav li {
    flex: 1;
}.local-nav a {
    display: flex;flex-direction: column;/* 侧轴居中对齐 因为是单行 */align-items: center;font-size: 12px;
}.local-nav li [class^="local-nav-icon"] {
    width: 32px;height: 32px;background-color: pink;margin-top: 8px;background: url(../images/localnav_bg.png) no-repeat 0 0;background-size: 32px auto;
}.local-nav li .local-nav-icon-icon2 {
    background-position: 0 -32px;
}.local-nav li .local-nav-icon-icon3 {
    background-position: 0 -64px;
}.local-nav li .local-nav-icon-icon4 {
    background-position: 0 -96px;
}.local-nav li .local-nav-icon-icon5 {
    background-position: 0 -128px;
}/* nav */nav {
    overflow: hidden;border-radius: 8px;margin: 0 4px 3px;
}.nav-common {
    display: flex;height: 88px;background-color: pink;
}.nav-common:nth-child(2) {
    margin: 3px 0;
}.nav-items {
    /* 不冲突的 */flex: 1;display: flex;flex-direction: column;
}.nav-items a {
    flex: 1;text-align: center;line-height: 44px;color: #fff;font-size: 14px;/* 文字阴影 */text-shadow: 1px 1px rgba(0, 0, 0, .2);
}.nav-items a:nth-child(1) {
    border-bottom: 1px solid #fff;
}.nav-items:nth-child(1) a {
    border: 0;background: url(../images/hotel.png) no-repeat bottom center;background-size: 121px auto;
}/* -n+2就是选择前面两个元素 */.nav-items:nth-child(-n+2) {
    border-right: 1px solid #fff;
}.nav-common:nth-child(1) {
    background: -webkit-linear-gradient(left, #FA5A55, #FA994D);
}.nav-common:nth-child(2) {
    background: -webkit-linear-gradient(left, #4B90ED, #53BCED);
}.nav-common:nth-child(3) {
    background: -webkit-linear-gradient(left, #34C2A9, #6CD559);
}/* subnav-entry */.subnav-entry {
    display: flex;border-radius: 8px;background-color: #fff;margin: 0 4px;flex-wrap: wrap;padding: 5px 0;
}.subnav-entry li {
    /* 里面的子盒子可以写 % 相对于父级来说的 */flex: 20%;
}.subnav-entry a {
    display: flex;flex-direction: column;align-items: center;
}.subnav-entry-icon {
    width: 28px;height: 28px;background-color: pink;margin-top: 4px;background: url(../images/subnav-bg.png) no-repeat;background-size: 28px auto;
}/* sales-box */.sales-box {
    border-top: 1px solid #bbb;background-color: #fff;margin: 4px;
}.sales-hd {
    position: relative;height: 44px;border-bottom: 1px solid #ccc;
}.sales-hd h2 {
    position: relative;text-indent: -999px;overflow: hidden;
}.sales-hd h2::after {
    position: absolute;top: 5px;left: 8px;content: "";width: 79px;height: 15px;background: url(../images/hot.png) no-repeat 0 -20px;background-size: 79px auto;
}.more {
    position: absolute;right: 5px;top: 0px;background: -webkit-linear-gradient(left, #FF506C, #FF6BC6);border-radius: 15px;padding: 3px 20px 3px 10px;color: #fff;
}.more::after {
    content: "";position: absolute;top: 9px;right: 9px;width: 7px;height: 7px;border-top: 2px solid #fff;border-right: 2px solid #fff;transform: rotate(45deg);
}.row {
    display: flex;
}.row a {
    flex: 1;border-bottom: 1px solid #eee;
}.row a:nth-child(1) {
    border-right: 1px solid #eee;
}.row a img {
    width: 100%;
}
window.addEventListener('load', function() {
    // alert(1);// 1. 获取元素 var focus = document.querySelector('.focus');var ul = focus.children[0];// 获得focus 的宽度var w = focus.offsetWidth;var ol = focus.children[1];// 2. 利用定时器自动轮播图图片var index = 0;var timer = setInterval(function() {
    index++;var translatex = -index * w;ul.style.transition = 'all .3s';ul.style.transform = 'translateX(' + translatex + 'px)';}, 2000);// 等着我们过渡完成之后,再去判断 监听过渡完成的事件 transitionend ul.addEventListener('transitionend', function() {
    // 无缝滚动if (index >= 3) {
    index = 0;// console.log(index);// 去掉过渡效果 这样让我们的ul 快速的跳到目标位置ul.style.transition = 'none';// 利用最新的索引号乘以宽度 去滚动图片var translatex = -index * w;ul.style.transform = 'translateX(' + translatex + 'px)';} else if (index < 0) {
    index = 2;ul.style.transition = 'none';// 利用最新的索引号乘以宽度 去滚动图片var translatex = -index * w;ul.style.transform = 'translateX(' + translatex + 'px)';}// 3. 小圆点跟随变化// 把ol里面li带有current类名的选出来去掉类名 removeol.querySelector('.current').classList.remove('current');// 让当前索引号 的小li 加上 current addol.children[index].classList.add('current');});// 4. 手指滑动轮播图 // 触摸元素 touchstart: 获取手指初始坐标var startX = 0;var moveX = 0; // 后面我们会使用这个移动距离所以要定义一个全局变量var flag = false;ul.addEventListener('touchstart', function(e) {
    startX = e.targetTouches[0].pageX;// 手指触摸的时候就停止定时器clearInterval(timer);});// 移动手指 touchmove: 计算手指的滑动距离, 并且移动盒子ul.addEventListener('touchmove', function(e) {
    // 计算移动距离moveX = e.targetTouches[0].pageX - startX;// 移动盒子: 盒子原来的位置 + 手指移动的距离 var translatex = -index * w + moveX;// 手指拖动的时候,不需要动画效果所以要取消过渡效果ul.style.transition = 'none';ul.style.transform = 'translateX(' + translatex + 'px)';flag = true; // 如果用户手指移动过我们再去判断否则不做判断效果e.preventDefault(); // 阻止滚动屏幕的行为});// 手指离开 根据移动距离去判断是回弹还是播放上一张下一张ul.addEventListener('touchend', function(e) {
    if (flag) {
    // (1) 如果移动距离大于50像素我们就播放上一张或者下一张if (Math.abs(moveX) > 50) {
    // 如果是右滑就是 播放上一张 moveX 是正值if (moveX > 0) {
    index--;} else {
    // 如果是左滑就是 播放下一张 moveX 是负值index++;}var translatex = -index * w;ul.style.transition = 'all .3s';ul.style.transform = 'translateX(' + translatex + 'px)';} else {
    // (2) 如果移动距离小于50像素我们就回弹var translatex = -index * w;ul.style.transition = 'all .1s';ul.style.transform = 'translateX(' + translatex + 'px)';}}// 手指离开的时候就重新开启定时器clearInterval(timer);timer = setInterval(function() {
    index++;var translatex = -index * w;ul.style.transition = 'all .3s';ul.style.transform = 'translateX(' + translatex + 'px)';}, 2000);});// 返回顶部模块制作var goBack = document.querySelector('.goBack');var nav = document.querySelector('nav');window.addEventListener('scroll', function() {
    if (window.pageYOffset >= nav.offsetTop) {
    goBack.style.display = 'block';} else {
    goBack.style.display = 'none';}});goBack.addEventListener('click', function() {
    window.scroll(0, 0);})
})

1.2.3 classList 属性

classList属性是HTML5新增的一个属性,返回元素的类名。但是ie10以上版本支持。

该属性用于在元素中添加,移除及切换 CSS 类。有以下方法

添加类:

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

focus.classList.add('current');

移除类:

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

focus.classList.remove('current');

切换类:

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

focus.classList.toggle('current');

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

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

1.2.4. 案例分析

  1. 小圆点跟随变化效果

  2. 把ol里面li带有current类名的选出来去掉类名 remove

  3. 让当前索引号的小li 加上 current add

  4. 但是,是等着过渡结束之后变化,所以这个写到 transitionend 事件里面

(img-DDhpnQpf-1591845376348)(images\1551796072(1)].jpg)

  1. 手指滑动轮播图
  2. 本质就是ul跟随手指移动,简单说就是移动端拖动元素
  3. 触摸元素touchstart: 获取手指初始坐标
  4. 移动手指touchmove: 计算手指的滑动距离,并且移动盒子
  5. 离开手指touchend: 根据滑动的距离分不同的情况
  6. 如果移动距离小于某个像素 就回弹原来位置
  7. 如果移动距离大于某个像素就上一张下一张滑动。
  8. 滑动也分为左滑动和右滑动判断的标准是 移动距离正负 如果是负值就是左滑 反之右滑
  9. 如果是左滑就播放下一张 (index++)
  10. 如果是右滑就播放上一张 (index–)

(img-iNpEtay5-1591845376349)(images\1551796363(1)].jpg)

(img-nqQqHv77-1591845376351)(images\1551796502(1)].jpg)

window.addEventListener('load', function() {
    // alert(1);// 1. 获取元素 var focus = document.querySelector('.focus');var ul = focus.children[0];// 获得focus 的宽度var w = focus.offsetWidth;var ol = focus.children[1];// 2. 利用定时器自动轮播图图片var index = 0;var timer = setInterval(function() {
    index++;var translatex = -index * w;ul.style.transition = 'all .3s';ul.style.transform = 'translateX(' + translatex + 'px)';}, 2000);// 等着我们过渡完成之后,再去判断 监听过渡完成的事件 transitionend ul.addEventListener('transitionend', function() {
    // 无缝滚动if (index >= 3) {
    index = 0;// console.log(index);// 去掉过渡效果 这样让我们的ul 快速的跳到目标位置ul.style.transition = 'none';// 利用最新的索引号乘以宽度 去滚动图片var translatex = -index * w;ul.style.transform = 'translateX(' + translatex + 'px)';} else if (index < 0) {
    index = 2;ul.style.transition = 'none';// 利用最新的索引号乘以宽度 去滚动图片var translatex = -index * w;ul.style.transform = 'translateX(' + translatex + 'px)';}// 3. 小圆点跟随变化// 把ol里面li带有current类名的选出来去掉类名 removeol.querySelector('.current').classList.remove('current');// 让当前索引号 的小li 加上 current addol.children[index].classList.add('current');});// 4. 手指滑动轮播图 // 触摸元素 touchstart: 获取手指初始坐标var startX = 0;var moveX = 0; // 后面我们会使用这个移动距离所以要定义一个全局变量var flag = false;ul.addEventListener('touchstart', function(e) {
    startX = e.targetTouches[0].pageX;// 手指触摸的时候就停止定时器clearInterval(timer);});// 移动手指 touchmove: 计算手指的滑动距离, 并且移动盒子ul.addEventListener('touchmove', function(e) {
    // 计算移动距离moveX = e.targetTouches[0].pageX - startX;// 移动盒子: 盒子原来的位置 + 手指移动的距离 var translatex = -index * w + moveX;// 手指拖动的时候,不需要动画效果所以要取消过渡效果ul.style.transition = 'none';ul.style.transform = 'translateX(' + translatex + 'px)';flag = true; // 如果用户手指移动过我们再去判断否则不做判断效果e.preventDefault(); // 阻止滚动屏幕的行为});// 手指离开 根据移动距离去判断是回弹还是播放上一张下一张ul.addEventListener('touchend', function(e) {
    if (flag) {
    // (1) 如果移动距离大于50像素我们就播放上一张或者下一张if (Math.abs(moveX) > 50) {
    // 如果是右滑就是 播放上一张 moveX 是正值if (moveX > 0) {
    index--;} else {
    // 如果是左滑就是 播放下一张 moveX 是负值index++;}var translatex = -index * w;ul.style.transition = 'all .3s';ul.style.transform = 'translateX(' + translatex + 'px)';} else {
    // (2) 如果移动距离小于50像素我们就回弹var translatex = -index * w;ul.style.transition = 'all .1s';ul.style.transform = 'translateX(' + translatex + 'px)';}}// 手指离开的时候就重新开启定时器clearInterval(timer);timer = setInterval(function() {
    index++;var translatex = -index * w;ul.style.transition = 'all .3s';ul.style.transform = 'translateX(' + translatex + 'px)';}, 2000);});// 返回顶部模块制作var goBack = document.querySelector('.goBack');var nav = document.querySelector('nav');window.addEventListener('scroll', function() {
    if (window.pageYOffset >= nav.offsetTop) {
    goBack.style.display = 'block';} else {
    goBack.style.display = 'none';}});goBack.addEventListener('click', function() {
    window.scroll(0, 0);})
})

1.3.1. 案例:返回顶部

当页面滚动某个地方,就显示,否则隐藏

点击可以返回顶部

1.3.2.案例分析

  1. 滚动某个地方显示
  2. 事件:scroll页面滚动事件
  3. 如果被卷去的头部(window.pageYOffset )大于某个数值
  4. 点击,window.scroll(0,0) 返回顶部

(img-9JLdfoOg-1591845376352)(images\1551797003(1)].jpg)

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

1.4. click 延时解决方案

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

解决方案:

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

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

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

? 原理就是:

  1. 当我们手指触摸屏幕,记录当前触摸时间
  2. 当我们手指离开屏幕, 用离开的时间减去触摸的时间
  3. 如果时间小于150ms,并且没有滑动过屏幕, 那么我们就定义为点击

代码如下:

//封装tap,解决click 300ms 延时
function tap (obj, callback) {
    var isMove = false;var startTime = 0; // 记录触摸时候的时间变量obj.addEventListener('touchstart', function (e) {
    startTime = Date.now(); // 记录触摸时间});obj.addEventListener('touchmove', function (e) {
    isMove = true;  // 看看是否有滑动,有滑动算拖拽,不算点击});obj.addEventListener('touchend', function (e) {
    if (!isMove && (Date.now() - startTime) < 150) {
      // 如果手指触摸和离开时间小于150ms 算点击callback && callback(); // 执行回调函数}isMove = false;  // 取反 重置startTime = 0;});
}
//调用 tap(div, function(){
       // 执行代码 });
  1. 使用插件。fastclick 插件解决300ms 延迟。

(img-wUx5W6bo-1591845376354)(images\1551797533(1)].jpg)

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><style>div {
     width: 50px;height: 50px;background-color: pink;}</style><script src="fastclick.js"></script>
</head><body><div></div><script>if ('addEventListener' in document) {
     document.addEventListener('DOMContentLoaded', function() {
     FastClick.attach(document.body);}, false);}var div = document.querySelector('div');div.addEventListener('click', function() {
     alert(11);})</script>
</body></html>

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

1.5. 移动端常用开发插件

1.5.1. 什么是插件

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

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

特点:它一般是为了解决某个问题而专门存在,其功能单一,并且比较小。

我们以前写的animate.js 也算一个最简单的插件

fastclick 插件解决 300ms 延迟。 使用延时

GitHub官网地址: https://github.com/ftlabs/fastclick

1.5.2. 插件的使用

  1. 引入 js 插件文件。

  2. 按照规定语法使用。

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

  4. GitHub官网地址: https://github.com/ftlabs/fastclick

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

1.5.3. Swiper 插件的使用

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

  1. 引入插件相关文件。
  2. 按照规定语法使用
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no,maximum-scale=1.0,minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><!-- 引入我们的css初始化文件 --><link rel="stylesheet" href="css/normalize.css"><!-- 引入我们首页的css --><link rel="stylesheet" href="css/index.css"><!-- 引入swipercss文件 --><link rel="stylesheet" href="css/swiper.min.css"><!-- 引入swiper js 文件 --><script src="js/swiper.min.js"></script><!-- 引入我们自己的js文件 --><script src="js/index.js"></script><title>Document</title>
</head><body><!-- 顶部 --><header class="app"><ul><li><img src="images/close.png" alt=""></li><li><img src="images/logo.png" alt=""></li><li>打开京东App,购物更轻松</li><li>立即打开</li></ul></header><!-- 搜索 --><div class="search-wrap"><div class="search-btn"></div><div class="search"><div class="jd-icon"></div><div class="sou"></div></div><div class="search-login">登陆</div></div><!-- 主体内容部分 --><div class="main-content"><!-- 滑动图 --><div class="slider"><!-- Swiper 注意不要更改里面的结构和类名 --><div class="swiper-container"><div class="swiper-wrapper"><div class="swiper-slide"><img src="upload/banner.dpg" alt=""></div><div class="swiper-slide"><img src="upload/banner1.dpg" alt=""></div><div class="swiper-slide"><img src="upload/banner2.dpg" alt=""></div><div class="swiper-slide"><img src="upload/banner3.dpg" alt=""></div></div><!-- Add Pagination --><div class="swiper-pagination"></div></div></div><!-- 小家电品牌日 --><div class="brand"><div><a href="#"><img src="upload/pic11.dpg" alt=""></a></div><div><a href="#"><img src="upload/pic22.dpg" alt=""></a></div><div><a href="#"><img src="upload/pic33.dpg" alt=""></a></div></div><!-- nav部分 --><nav class="clearfix"><a href=""><img src="upload/nav1.webp" alt=""><span>京东超市</span></a><a href=""><img src="upload/nav2.webp" alt=""><span>京东超市</span></a><a href=""><img src="upload/nav1.webp" alt=""><span>京东超市</span></a><a href=""><img src="upload/nav1.webp" alt=""><span>京东超市</span></a><a href=""><img src="upload/nav1.webp" alt=""><span>京东超市</span></a><a href=""><img src="upload/nav3.webp" alt=""><span>京东超市</span></a><a href=""><img src="upload/nav1.webp" alt=""><span>京东超市</span></a><a href=""><img src="upload/nav1.webp" alt=""><span>京东超市</span></a><a href=""><img src="upload/nav1.webp" alt=""><span>京东超市</span></a><a href=""><img src="upload/nav1.webp" alt=""><span>京东超市</span></a></nav><!-- 新闻模块 --><div class="news"><a href="#"><img src="upload/new1.dpg" alt=""></a><a href="#"><img src="upload/new2.dpg" alt=""></a><a href="#"><img src="upload/new3.dpg" alt=""></a></div></div>
</body></html>
body {
    width: 100%;min-width: 320px;max-width: 640px;margin: 0 auto;font-size: 14px;font-family: -apple-system, Helvetica, sans-serif;color: #666;line-height: 1.5;
}/*点击高亮我们需要清除清除 设置为transparent 完成透明*/* {
    -webkit-tap-highlight-color: transparent;
}/*在移动端浏览器默认的外观在iOS上加上这个属性才能给按钮和输入框自定义样式*/input {
    -webkit-appearance: none;
}/*禁用长按页面时的弹出菜单*/img, a {
    -webkit-touch-callout: none;
}a {
    color: #666;text-decoration: none;
}ul {
    margin: 0;padding: 0;list-style: none;
}img {
    vertical-align: middle;
}div {
    /* css3 盒子模型 */box-sizing: border-box;
}.clearfix:after {
    content: "";display: block;line-height: 0;visibility: hidden;height: 0;clear: both;
}.app {
    height: 45px;
}.app ul li {
    float: left;height: 45px;line-height: 45px;background-color: #333333;text-align: center;color: #fff;
}.app ul li:nth-child(1) {
    width: 8%;
}.app ul li:nth-child(1) img {
    width: 10px;
}.app ul li:nth-child(2) {
    width: 10%;
}.app ul li:nth-child(2) img {
    width: 30px;vertical-align: middle;
}.app ul li:nth-child(3) {
    width: 57%;
}.app ul li:nth-child(4) {
    width: 25%;background-color: #F63515;
}/* 搜索 */.search-wrap {
    position: fixed;overflow: hidden;width: 100%;height: 44px;min-width: 320px;max-width: 640px;z-index: 9999;
}.search-btn {
    position: absolute;top: 0;left: 0;width: 40px;height: 44px;
}.search-btn::before {
    content: "";display: block;width: 20px;height: 18px;background: url(../images/s-btn.png) no-repeat;background-size: 20px 18px;margin: 14px 0 0 15px;
}.search-login {
    position: absolute;right: 0;top: 0;width: 40px;height: 44px;color: #fff;line-height: 44px;
}.search {
    position: relative;height: 30px;background-color: #fff;margin: 0 50px;border-radius: 15px;margin-top: 7px;
}.jd-icon {
    width: 20px;height: 15px;position: absolute;top: 8px;left: 13px;background: url(../images/jd.png) no-repeat;background-size: 20px 15px;
}.jd-icon::after {
    content: "";position: absolute;right: -8px;top: 0;display: block;width: 1px;height: 15px;background-color: #ccc;
}.sou {
    position: absolute;top: 8px;left: 50px;width: 18px;height: 15px;background: url(../images/jd-sprites.png) no-repeat -81px 0;background-size: 200px auto;
}.slider img {
    width: 100%;
}/* 复制swiper css样式 */.swiper-container {
    width: 100%;height: 100%;
}.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;
}.swiper-pagination-bullet {
    background: #fff!important;
}/* 品牌日 */.brand {
    overflow: hidden;border-radius: 10px 10px 0 0;
}.brand div {
    float: left;width: 33.33%;
}.brand div img {
    width: 100%;
}/* nav */nav {
    padding-top: 5px;
}nav a {
    float: left;width: 20%;text-align: center;
}nav a img {
    width: 40px;margin: 10px 0;
}nav a span {
    display: block;
}/* news */.news {
    margin-top: 20px;
}.news img {
    width: 100%;
}.news a {
    float: left;box-sizing: border-box;
}.news a:nth-child(1) {
    width: 50%;
}/* .news a:nth-child(2), .news a:nth-child(3), {width: 25%; } *//* n+2 就是从从2个往后面选 */.news a:nth-child(n+2) {
    width: 25%;border-left: 1px solid #ccc;
}/* .news a:nth-child(3) {width: 25%; } */
window.addEventListener('load', function() {
    var swiper = new Swiper('.swiper-container', {
    spaceBetween: 30,centeredSlides: true,autoplay: {
    delay: 5000,disableOnInteraction: false,},pagination: {
    el: '.swiper-pagination',clickable: true,},navigation: {
    nextEl: '.swiper-button-next',prevEl: '.swiper-button-prev',},});
})

1.5.4. 其他移动端常见插件

lsuperslide: http://www.superslide2.com/

l iscroll: https://github.com/cubiq/iscroll

1.5.5. 插件的使用总结

1.确认插件实现的功能

2.去官网查看使用说明

3.下载插件

4.打开demo实例文件,查看需要引入的相关文件,并且引入

5.复制demo实例文件中的结构html,样式css以及js代码

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

H5 给我们提供了 video 标签,但是浏览器的支持情况不同。

不同的视频格式文件,我们可以通过source解决。

但是外观样式,还有暂停,播放,全屏等功能我们只能自己写代码解决。

这个时候我们可以使用插件方式来制作。

我们可以通过 JS 修改元素的大小、颜色、位置等样式。

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><link rel="stylesheet" href="zy.media.min.css"><script src="zy.media.min.js"></script><style type="text/css">#modelView {
     background-color: #DDDDDD;z-index: 0;opacity: 0.7;height: 100%;width: 100%;position: relative;}.playvideo {
     padding-top: auto;z-index: 9999;position: relative;width: 300px;height: 200px;}.zy_media {
     z-index: 999999999}</style></head><body><div class="playvideo"><div class="zy_media"><video data-config='{
     "mediaTitle": "小蝴蝶"}'><source src="mov.mp4" type="video/mp4">您的浏览器不支持HTML5视频</video></div><div id="modelView">&nbsp;</div></div><script>zymedia('video', {
     autoplay: false});</script></body></html>

1.6. 移动端常用开发框架

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

框架,顾名思义就是一套架构,它会基于自身的特点向用户提供一套较为完整的解决方案。框架的控制权在框架本身,使用者要按照框架所规定的某种规范进行开发。

插件一般是为了解决某个问题而专门存在,其功能单一,并且比较小。

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

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

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

插件: 小而专一,某个功能的解决方案

1.6.2. Bootstrap

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

它能开发PC端,也能开发移动端

Bootstrap JS插件使用步骤:

1.引入相关js 文件

2.复制HTML 结构

3.修改对应样式

4.修改相应JS 参数

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"><script src="bootstrap/js/jquery.min.js"></script><script src="bootstrap/js/bootstrap.min.js"></script><style>.focus {
     width: 800px;height: 300px;background-color: pink;margin: 100px auto;}.carousel,.carousel img {
     width: 100%;height: 300px!important;}</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="upload/banner.dpg" alt="..."><div class="carousel-caption">这是我的图片1</div></div><div class="item"><img src="upload/banner1.dpg" alt="..."><div class="carousel-caption">这是我的图片2</div></div><div class="item"><img src="upload/banner2.dpg" alt="..."><div class="carousel-caption">这是我的图片3</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><script>$('.carousel').carousel({
     interval: 2000})</script>
</body></html>

1.7. 本地存储

随着互联网的快速发展,基于网页的应用越来越普遍,同时也变的越来越复杂,为了满足各种各样的需求,会经常性在本地存储大量的数据,HTML5规范提出了相关解决方案。

1.7.1.本地存储特性

1、数据存储在用户浏览器中

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

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

4、只能存储字符串,可以将对象JSON.stringify() 编码后存储

1.7.2.window.sessionStorage

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

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

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

存储数据:

sessionStorage.setItem(key, value)

获取数据:

sessionStorage.getItem(key)

删除数据:

sessionStorage.removeItem(key)

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

sessionStorage.clear()
<body><input type="text"><button class="set">存储数据</button><button class="get">获取数据</button><button class="remove">删除数据</button><button class="del">清空所有数据</button><script>console.log(localStorage.getItem('username'));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);sessionStorage.setItem('pwd', val);});get.addEventListener('click', function() {
     // 当我们点击了之后,就可以把表单里面的值获取过来console.log(sessionStorage.getItem('uname'));});remove.addEventListener('click', function() {
     // sessionStorage.removeItem('uname');});del.addEventListener('click', function() {
     // 当我们点击了之后,清除所有的sessionStorage.clear();});</script>
</body>

1.7.3.window.localStorage

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

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

  1. 以键值对的形式存储使用

存储数据:

localStorage.setItem(key, value)

获取数据:

localStorage.getItem(key)

删除数据:

localStorage.removeItem(key)

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

localStorage.clear()
<body><input type="text"><button class="set">存储数据</button><button class="get">获取数据</button><button class="remove">删除数据</button><button class="del">清空所有数据</button><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;localStorage.setItem('username', val);})get.addEventListener('click', function() {
     console.log(localStorage.getItem('username'));})remove.addEventListener('click', function() {
     localStorage.removeItem('username');})del.addEventListener('click', function() {
     localStorage.clear();})</script>
</body>

1.7.4.案例:记住用户名

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

案例分析
  1. 把数据存起来,用到本地存储

  2. 关闭页面,也可以显示用户名,所以用到localStorage

  3. 打开页面,先判断是否有这个用户名,如果有,就在表单里面显示用户名,并且勾选复选框

  4. 当复选框发生改变的时候change事件

  5. 如果勾选,就存储,否则就移除

(img-UCoWzc1w-1591845376355)(images\1551800263(1)].jpg)

<body><input type="text" id="username"> <input type="checkbox" name="" id="remember"> 记住用户名<script>var username = document.querySelector('#username');var remember = document.querySelector('#remember');if (localStorage.getItem('username')) {
     username.value = localStorage.getItem('username');remember.checked = true;}remember.addEventListener('change', function() {
     if (this.checked) {
     localStorage.setItem('username', username.value)} else {
     localStorage.removeItem('username');}})</script>
</body>

1.8. 每日作业-Web APIs第07天

1 - 移动端轮播图

  • 题目描述

    把今天课上讲的携程的轮播图写一遍

  • 训练目标

    能够独自完成移动端轮播图的制作

  • 训练提示

    1.把轮播图中的第一张和最后一张分别复制一份放到前后

    2.先做页面自动轮播效果, 利用translate移动

    3.添加检测过渡完成事件 transitionend 来完成无缝滚动

    4.利用classList完成li的小圆点切换

    5.利用touchstart,touchmove, touchend来完成手指移动轮播图

2 - 返回顶部案例

  • 题目描述

    把课上的返回顶部案例写一遍

  • 训练目标

    能够明白pc端和移动端的代码是一样的,可以通用

  • 训练提示

    1. 滚动某个地方显示
    2. 事件:scroll页面滚动事件
    3. 如果被卷去的头部(window.pageYOffset )大于某个数值
    4. 点击返回顶部

3 - 插件轮播图

  • 题目描述

    利用插件多尝试几个不同的轮播图

  • 训练目标

    能够使用插件

4 - 记住用户名

  • 题目描述

    把课上的记住用户名案例写一遍

  • 训练目标

    能够使用本地存储

  • 训练提示

    1. 把数据存起来,用到本地存储
    2. 关闭页面,也可以显示用户名,
    3. 打开页面,先判断是否有这个用户名,如果有,就在表单里面显示用户名,并且勾选复选框
    4. 当复选框发生改变的时候change事件
    5. 如果勾选,就存储,否则就移除

1.9. 随堂测验

考点:touchEvent

单选题

以下哪些不属于touch事件对象的属性()

A.changedTouches属性
B.targetTouches属性
C.touches属
D.touch属性

答案: D

解析: 本题考查的是touchEvent中常见的属性。答案D错误,因为没有这个属性。

难度: ☆☆

考点:touch事件类型

单选题

以下关于touch事件说法错误的是()

A.touchstart是指手指按压下去后触发
B.touchmove是手指按压并且滑动后触发
C.touchend是手指松开后触发
D.touchover是指手指松开后触发

答案: D

解析: 本题考查的是touch相关的事件类型。答案D错误,因为没有这个事件。

难度: ☆☆

考点:scroll系列属性的使用

多选题

以下关于touch事件说法正确的是()

A.click是鼠标事件,但是在移动端也能使用。~
B.mousedown和mouseup是鼠标事件,在移动端能够使用。~
C.鼠标事件click在移动端比touchstart执行效率高~
D.鼠标事件在移动端不能够使用~
E.在移动端,touch事件比鼠标事件执行效率高

答案: ABE

解析: 本题考查的是touch事件和鼠标事件在移动端的区别。答案C错误,在移动端touch相关的事件类型比鼠标事件执行效率高;答案D错误,鼠标事件在移动端也可以使用

难度: ☆☆☆

考点:touchEvent

多选题

以下关于touch事件对象说法正确的是()

A.touches属性可以获取屏幕上的所有手指的列表
B.changedTouches属性在touchsend事件处理程序中得到改变的手指列表
C.targetTouches属性和touches在手指按下和移动中都可以获取手指列表
D.手指列表中的某一个手指的clientX和pageX在移动端可以互相使用
E.在click事件中也可以获取touches属性

答案:ABCD

解析:本题考查的是touchEvent创建的属性及作用。答案E错误,鼠标事件中不存在touches属性

难度: ☆☆☆

  相关解决方案