目录
概述
常见的触屏事件
触屏touch事件 | 说明 |
touchstart | 手指触摸到一个DOM元素时触发 |
touchmove | 手指在一个DOM元素上滑动时触发 |
touchend | 手指从一个DOM元素上移开时触发 |
<body>
<div></div>
<script>
var div = document.querySelector('div');
// 触摸到div触发
div.addEventListener('touchstart', function () {
console.log('start');
})
// div中拖拽触发
div.addEventListener('touchmove', function () {
console.log('move');
})
// 不触摸div触发
div.addEventListener('touchend', function () {
console.log('end');
})
</script>
</body>
触摸事件对象(TouchEvent)
触摸列表 | 说明 |
touches | 正在触摸屏幕的所有手指的一个列表 |
targetTouches | 正在触摸当前DOM元素上的手指的一个列表 |
changedTouches | 手指状态发生了改变的列表,从无到有,从有到无变化 |
移动端拖动元素
<style>
div {
position: absolute;
width: 150px;
left: 0;
top: 0;
height: 150px;
background-color: pink;
}
</style>
<body>
<div></div>
<script>
window.onload = function () {
// 获取盒子
var div = document.querySelector('div');
// 手指初始坐标
var startX = 0;
var startY = 0;
// 盒子原来位置
var x = 0;
var y = 0;
// touchstart 触摸元素事件
div.addEventListener('touchstart', function (e) {
startX = e.targetTouches[0].pageX;
startY = e.targetTouches[0].pageY;
x = div.offsetLeft;
y = div.offsetTop;
})
// touchmove 拖拽事件
div.addEventListener('touchmove', function (e) {
// 移动坐标 = 当前坐标 - 初始坐标
var moveX = e.targetTouches[0].pageX - startX;
var moveY = e.targetTouches[0].pageY - startY;
// 实际坐标 = 移动坐标 + 原来坐标
div.style.left = moveX + x + 'px';
div.style.top = moveY + y + 'px';
e.preventDefault();
})
}
</script>
</body>
效果:
classList属性
添加类
移除类
切换类
注意:以上所有方法,类名不带点。
返回顶部案例
<style>
nav,
main,
header,
footer {
width: 100%;
}
nav {
height: 20px;
background-color: pink;
}
header {
height: 250px;
background-color: green;
}
main {
height: 800px;
background-color: blue;
}
footer {
height: 250px;
background-color: red;
}
div {
display: none;
position: fixed;
right: 0;
top: 450px;
width: 50px;
height: 50px;
background-color: rgb(64, 130, 196);
}
</style>
<body>
<nav></nav>
<header></header>
<main></main>
<footer></footer>
<div></div>
<script>
// 获取返回顶部盒子
var div = document.querySelector('div');
var main = document.querySelector('main');
var mainOffsetTop = main.offsetTop;
// 当滚动距离超过main上面的距离时 显示返回顶部模块 否则显示
window.addEventListener('scroll', function () {
if (window.pageYOffset >= mainOffsetTop) {
div.style.display = 'block';
} else {
div.style.display = 'none';
}
})
// 点击返回顶部
div.onclick = function () {
window.scroll(0, 0);
}
</script>
</body>