1.M端事件(移动端事件)
//在谷歌浏览器中可以模拟安卓端和ios端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 300px;
height: 300px;
background-color: aqua;
}
</style>
</head>
<body>
<div></div>
<script>
//移动端事件
const div = document.querySelector('div');
div.addEventListener('touchstart', function () {
//touchstart开始触摸
console.log('touchstart');
})
//touchmove移动
div.addEventListener('touchmove', function () {
console.log('touchmove');
})
//touchend结束触摸(手指离开屏幕)
div.addEventListener('touchend', function () {
console.log('touchend');
})
</script>
</body>
</html>
2.插件
2.1插件-swiper(pc端和移动端都适配)
//使用网页源代码实现demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Swiper demo</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="./css/swiper.min.css">
<!-- Demo styles -->
<style>
html,
body {
position: relative;
height: 100%;
}
body {
background: #fff;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: 0;
padding: 0;
}
.swiper-container {
width: 500px;
height: 500px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
}
.swiper-slide {
background-position: center;
background-size: cover;
}
</style>
</head>
<body>
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" style="background-image:url(img/njs1.jpg)"></div>
<div class="swiper-slide" style="background-image:url(img/njs2.jpg)"></div>
<div class="swiper-slide" style="background-image:url(img/njs3.jpg)"></div>
<div class="swiper-slide" style="background-image:url(img/njs4.jpg)"></div>
<div class="swiper-slide" style="background-image:url(img/njs5.jpg)"></div>
<div class="swiper-slide" style="background-image:url(img/njs6.jpg)"></div>
</div>
<!-- Add Pagination -->
<!-- 自动生成的小圆点 -->
<div class="swiper-pagination"></div>
</div>
<!-- Swiper JS -->
<script src="./js/swiper.js"></script>
<!-- Initialize Swiper -->
<script>
var swiper = new Swiper('.swiper-container', {
//分页器
pagination: '.swiper-pagination',
effect: 'cube',
grabCursor: true,
cube: {
shadow: true,
slideShadows: true,
shadowOffset: 20,
shadowScale: 0.94,
},
//无限轮播
loop: true,
//自动播放
autoplay: 1000
});
</script>
</body>
</html>
效果:
2.2 插件—AlloyFinger
github地址
[手势库介绍](超小手势库alloyfinger及其vue版实现深入解析alloyfinger是一款非常轻量的开源手势库,由于其轻量、基 - 掘金)
2.2.1 用法1:创建一个新的js文件,将以下代码复制到文件中
/* AlloyFinger v0.1.7
* By dntzhang
* Github: https://github.com/AlloyTeam/AlloyFinger
* Note By keenjaan
* Github: https://github.com/keenjaan
*/
; (function () {
// 计算距离和角度等的数学公式
// 根据两边的长度求直角三角形斜边长度(主要用于求两点距离)
function getLen(v) {
return Math.sqrt(v.x * v.x + v.y * v.y);
}
// 主要用于计算两次手势状态间的夹角的辅助函数
function dot(v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
}
// 计算两次手势状态间的夹角
function getAngle(v1, v2) {
var mr = getLen(v1) * getLen(v2);
if (mr === 0) return 0;
var r = dot(v1, v2) / mr;
if (r > 1) r = 1;
return Math.acos(r);
}
// 计算夹角的旋转方向,(逆时针大于0,顺时针小于0)
function cross(v1, v2) {
return v1.x * v2.y - v2.x * v1.y;
}
// 将角度转换为弧度,并且绝对值
function getRotateAngle(v1, v2) {
var angle = getAngle(v1, v2);
if (cross(v1, v2) > 0) {
angle *= -1;
}
return angle * 180 / Math.PI;
}
// 用于处理手势监听函数的构造函数
var HandlerAdmin = function(el) {
this.handlers = []; // 监听函数列表
this.el = el; // 监听元素
};
// 构造函数的添加监听函数的方法
HandlerAdmin.prototype.add = function(handler) {
this.handlers.push(handler);
}
// 构造函数的删除监听函数的方法
HandlerAdmin.prototype.del = function(handler) {
if(!handler) this.handlers = []; // handler为假值时,代表清空监听函数列表
for(var i=this.handlers.length; i>=0; i--) {
if(this.handlers[i] === handler) {
this.handlers.splice(i, 1);
}
}
}
// 触发用户事件监听回调函数
HandlerAdmin.prototype.dispatch = function() {
for(var i=0,len=this.handlers.length; i<len; i++) {
var handler = this.handlers[i];
if(typeof handler === 'function') handler.apply(this.el, arguments);
}
}
// 实例化处理监听函数的对象
function wrapFunc(el, handler) {
var handlerAdmin = new HandlerAdmin(el);
handlerAdmin.add(handler); // 添加监听函数
return handlerAdmin; // 返回实例
}
// 手势的构造函数
var AlloyFinger = function (el, option) {
this.element = typeof el == 'string' ? document.querySelector(el) : el; // 绑定事件的元素
// 绑定原型上start, move, end, cancel函数的this对象为 AlloyFinger实例
this.start = this.start.bind(this);
this.move = this.move.bind(this);
this.end = this.end.bind(this);
this.cancel = this.cancel.bind(this);
// 绑定原生的 touchstart, touchmove, touchend, touchcancel事件。
this.element.addEventListener("touchstart", this.start, false);
this.element.addEventListener("touchmove", this.move, false);
this.element.addEventListener("touchend", this.end, false);
this.element.addEventListener("touchcancel", this.cancel, false);
// 保存当有两个手指以上时,两个手指间横纵坐标的差值,用于计算两点距离
this.preV = { x: null, y: null };
this.pinchStartLen = null; // 两个手指间的距离
this.zoom = 1; // 初始缩放比例
this.isDoubleTap = false; // 是否双击
var noop = function () { }; // 空函数,没有绑定事件时,传入的函数
// 对14种手势,分别实例化监听函数对象,根据option的值添加相关监听函数,没有就添加空函数。
this.rotate = wrapFunc(this.element, option.rotate || noop);
this.touchStart = wrapFunc(this.element, option.touchStart || noop);
this.multipointStart = wrapFunc(this.element, option.multipointStart || noop);
this.multipointEnd = wrapFunc(this.element, option.multipointEnd || noop);
this.pinch = wrapFunc(this.element, option.pinch || noop);
this.swipe = wrapFunc(this.element, option.swipe || noop);
this.tap = wrapFunc(this.element, option.tap || noop);
this.doubleTap = wrapFunc(this.element, option.doubleTap || noop);
this.longTap = wrapFunc(this.element, option.longTap || noop);
this.singleTap = wrapFunc(this.element, option.singleTap || noop);
this.pressMove = wrapFunc(this.element, option.pressMove || noop);
this.touchMove = wrapFunc(this.element, option.touchMove || noop);
this.touchEnd = wrapFunc(this.element, option.touchEnd || noop);
this.touchCancel = wrapFunc(this.element, option.touchCancel || noop);
this.delta = null; // 用于判断是否是双击的时间戳
this.last = null; // 记录时间戳的变量
this.now = null; // 记录时间戳的变量
this.tapTimeout = null; //tap事件执行的定时器
this.singleTapTimeout = null; // singleTap执行的定时器
this.longTapTimeout = null; // longTap执行的定时器
this.swipeTimeout = null; // swipe执行的定时器
this.x1 = this.x2 = this.y1 = this.y2 = null; // start时手指的坐标x1, y1, move时手指的坐标x2, y2
this.preTapPosition = { x: null, y: null }; // 记住start时,手指的坐标
};
AlloyFinger.prototype = {
start: function (evt) {
if (!evt.touches) return; // touches手指列表,没有就return
this.now = Date.now(); // 记录当前事件点
this.x1 = evt.touches[0].pageX; // 第一个手指x坐标
this.y1 = evt.touches[0].pageY; // 第一个手指y坐标
this.delta = this.now - (this.last || this.now); // 时间戳
this.touchStart.dispatch(evt); // 触发touchStart事件
if (this.preTapPosition.x !== null) {
// 不是第一次触摸屏幕时,比较两次触摸时间间隔,两次触摸间隔小于250ms,触摸点的距离小于30px时记为双击。
this.isDoubleTap = (this.delta > 0 && this.delta <= 250 && Math.abs(this.preTapPosition.x - this.x1) < 30 && Math.abs(this.preTapPosition.y - this.y1) < 30);
}
this.preTapPosition.x = this.x1; // 将此次的触摸坐标保存到preTapPosition。
this.preTapPosition.y = this.y1;
this.last = this.now; // 记录本次触摸时间点
var preV = this.preV, // 获取记录的两点坐标差值
len = evt.touches.length; // 手指个数
if (len > 1) { // 手指个数大于1
this._cancelLongTap(); // 取消longTap定时器
this._cancelSingleTap(); // 取消singleTap定时器
var v = { x: evt.touches[1].pageX - this.x1, y: evt.touches[1].pageY - this.y1 };
// 计算两个手指间横纵坐标差,并保存到prev对象中,也保存到this.preV中。
preV.x = v.x;
preV.y = v.y;
this.pinchStartLen = getLen(preV); // 计算两个手指的间距
this.multipointStart.dispatch(evt); // 触发multipointStart事件
}
// 开启longTap事件定时器,如果750ms内定时器没有被清除则触发longTap事件。
this.longTapTimeout = setTimeout(function () {
this.longTap.dispatch(evt);
}.bind(this), 750);
},
move: function (evt) {
if (!evt.touches) return;
var preV = this.preV, // start方法中保存的两点横纵坐标差值。
len = evt.touches.length, // 手指个数
currentX = evt.touches[0].pageX, // 第一个手指的x坐标
currentY = evt.touches[0].pageY; // 第一个手指的y坐标
this.isDoubleTap = false; // 移动了就不能是双击事件了
if (len > 1) {
// 获取当前两点横纵坐标的差值,保存到v对象中。
var v = { x: evt.touches[1].pageX - currentX, y: evt.touches[1].pageY - currentY };
// start保存的preV不为空,pinchStartLen大于0
if (preV.x !== null) {
if (this.pinchStartLen > 0) {
// 当前两点的距离除以start中两点距离,求出缩放比,挂载到evt对象中
evt.zoom = getLen(v) / this.pinchStartLen;
this.pinch.dispatch(evt); // 触发pinch事件
}
evt.angle = getRotateAngle(v, preV); // 计算旋转的角度,挂载到evt对象中
this.rotate.dispatch(evt); // 触发rotate事件
}
preV.x = v.x; // 将move中的两个手指的横纵坐标差值赋值给preV,同时也改变了this.preV
preV.y = v.y;
} else {
// 出列一根手指的pressMove手势
// 第一次触发move时,this.x2为null,move执行完会有给this.x2赋值。
if (this.x2 !== null) {
// 用本次的move坐标减去上一次move坐标,得到x,y方向move距离。
evt.deltaX = currentX - this.x2;
evt.deltaY = currentY - this.y2;
} else {
// 第一次执行move,所以移动距离为0,将evt.deltaX,evt.deltaY赋值为0.
evt.deltaX = 0;
evt.deltaY = 0;
}
// 触发pressMove事件
this.pressMove.dispatch(evt);
}
// 触发touchMove事件,挂载不同的属性给evt对象抛给用户
this.touchMove.dispatch(evt);
// 取消长按定时器,750ms内可以阻止长按事件。
this._cancelLongTap();
this.x2 = currentX; // 记录当前第一个手指坐标
this.y2 = currentY;
if (len > 1) {
evt.preventDefault(); // 两个手指以上阻止默认事件
}
},
end: function (evt) {
if (!evt.changedTouches) return;
// 取消长按定时器,750ms内会阻止长按事件
this._cancelLongTap();
var self = this; // 保存当前this对象。
// 如果当前留下来的手指数小于2,触发multipointEnd事件
if (evt.touches.length < 2) {
this.multipointEnd.dispatch(evt);
}
// this.x2或this.y2存在代表触发了move事件。
// Math.abs(this.x1 - this.x2)代表在x方向移动的距离。
// 故就是在x方向或y方向移动的距离大于30px时则触发swipe事件
if ((this.x2 && Math.abs(this.x1 - this.x2) > 30) ||
(this.y2 && Math.abs(this.y1 - this.y2) > 30)) {
// 计算swipe的方向并写入evt对象。
evt.direction = this._swipeDirection(this.x1, this.x2, this.y1, this.y2);
this.swipeTimeout = setTimeout(function () {
self.swipe.dispatch(evt); // 异步触发swipe事件
}, 0)
} else {
this.tapTimeout = setTimeout(function () {
self.tap.dispatch(evt); // 异步触发tap事件
// trigger double tap immediately
if (self.isDoubleTap) { // start方法中计算的满足双击条件时
self.doubleTap.dispatch(evt); // 触发双击事件
clearTimeout(self.singleTapTimeout); // 清楚singleTap事件定时器
self.isDoubleTap = false; // 重置双击条件
}
}, 0)
if (!self.isDoubleTap) { // 如果不满足双击条件
self.singleTapTimeout = setTimeout(function () {
self.singleTap.dispatch(evt); // 触发singleTap事件
}, 250);
}
}
this.touchEnd.dispatch(evt); // 触发touchEnd事件
// end结束后重置相关的变量
this.preV.x = 0;
this.preV.y = 0;
this.zoom = 1;
this.pinchStartLen = null;
this.x1 = this.x2 = this.y1 = this.y2 = null;
},
cancel: function (evt) {
// 关闭所有定时器
clearTimeout(this.singleTapTimeout);
clearTimeout(this.tapTimeout);
clearTimeout(this.longTapTimeout);
clearTimeout(this.swipeTimeout);
this.touchCancel.dispatch(evt);
},
_cancelLongTap: function () {
clearTimeout(this.longTapTimeout); // 关闭longTap定时器
},
_cancelSingleTap: function () {
clearTimeout(this.singleTapTimeout); // 关闭singleTap定时器
},
_swipeDirection: function (x1, x2, y1, y2) {
// 判断swipe方向
return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
},
// 给14中手势中一种手势添加监听函数
on: function(evt, handler) {
if(this[evt]) { // 事件名在这14中之中,才添加函数到监听事件中
this[evt].add(handler);
}
},
// 给14中手势中一种手势移除监听函数
off: function(evt, handler) {
if(this[evt]) { // 事件名在这14中之中,才移除相应监听函数
this[evt].del(handler);
}
},
// 清空,重置所有数据
destroy: function() {
// 关闭所有定时器
if(this.singleTapTimeout) clearTimeout(this.singleTapTimeout);
if(this.tapTimeout) clearTimeout(this.tapTimeout);
if(this.longTapTimeout) clearTimeout(this.longTapTimeout);
if(this.swipeTimeout) clearTimeout(this.swipeTimeout);
// 移除touch的四个事件
this.element.removeEventListener("touchstart", this.start);
this.element.removeEventListener("touchmove", this.move);
this.element.removeEventListener("touchend", this.end);
this.element.removeEventListener("touchcancel", this.cancel);
// 清除所有手势的监听函数
this.rotate.del();
this.touchStart.del();
this.multipointStart.del();
this.multipointEnd.del();
this.pinch.del();
this.swipe.del();
this.tap.del();
this.doubleTap.del();
this.longTap.del();
this.singleTap.del();
this.pressMove.del();
this.touchMove.del();
this.touchEnd.del();
this.touchCancel.del();
// 重置所有变量
this.preV = this.pinchStartLen = this.zoom = this.isDoubleTap = this.delta = this.last = this.now = this.tapTimeout = this.singleTapTimeout = this.longTapTimeout = this.swipeTimeout = this.x1 = this.x2 = this.y1 = this.y2 = this.preTapPosition = this.rotate = this.touchStart = this.multipointStart = this.multipointEnd = this.pinch = this.swipe = this.tap = this.doubleTap = this.singleTap = this.pressMove = this.touchMove = this.touchEnd = this.touchCancel = null;
return null;
}
};
// 如果当前环境支持module,exports等es6语法,则导出AlloyFingerPlugin模块
if (typeof module !== 'undefined' && typeof exports === 'object') {
module.exports = AlloyFinger;
} else { // 否则将AlloyFingerPlugin注册到全局对象
window.AlloyFinger = AlloyFinger;
}
})();
2.2.2 用法二:
无需下载,打开自在线文件地址即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background: pink;
}
</style>
</head>
<body>
<div></div>
<!-- 打开其在线地址 -->
<script src="https://unpkg.com/alloyfinger@0.1.16/alloy_finger.js"></script>
<script>
//注意,direction只在移动端向时才有效,所以要在浏览器内改为移动端查看
const div = document.querySelector("div")
new AlloyFinger(div, {
swipe: function (e) {
//事件.手指 控制台会返回left right up down
console.log("swipe" + e.direction)
}
})
</script>
</body>
</html>
2.3案例
2.3.1foreach的使用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 初始化数据
const arr = [
{ name: "周杰伦", tel: "13411112222" },
{ name: "刘德华", tel: "13511112222" },
{ name: "张学友", tel: "13711112222" },
{ name: "岳云鹏", tel: "13911112222" }
]
//数组.foreach(function(数组每一项,数组每一项的索引){})
arr.forEach(function (item, index) {
console.log(item)//数组的每一项
console.log(index)//每一项的索引
})
</script>
</body>
</html>
结果:
2.3.2字符串截取方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//字符串截取方法
const str = "newjeans"
// 截取字符串(字符串.substring(开始索引,结束索引))
//注意:索引从0开始,且结束索引不包含在内
//结束索引可有可无
console.log(str.substring(0, 3))
</script>
</body>
</html>
结果: