目录
概述
移动端浏览器兼容性较好,不需要考虑以前JS的兼容性问题,可以放心的使用原生JS书写效果,移动端也有自己独特的地方。比如touch(也称触摸事件),touch对象代表一个触摸点。触摸点可能是一根手指,也可能是一根触摸笔。
常见的触屏事件
触屏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)
TouchEvent是一类描述手指在触摸平面(触摸屏、触摸板等)的状态变化的事件。这类事件用于描述一个或多个触点,使开发者可以检测触点的移动,触点的增加和减少等等。
touchstart、touchmove、touchend三个事件都有各自的事件对象
触摸事件对象重点看三个常见对象:
触摸列表 | 说明 |
touches | 正在触摸屏幕的所有手指的一个列表 |
targetTouches | 正在触摸当前DOM元素上的手指的一个列表 |
changedTouches | 手指状态发生了改变的列表,从无到有,从有到无变化 |
因为平时都是给元素注册触摸对象,所以重点记住targetTouches
移动端拖动元素
<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属性
classList属性是HTML5新增的一个属性,返回元素的类名。但是IE10以上才支持。
该属性在元素中添加,移除及切换CSS类。有以下方法:
添加类
element.classList.add(‘类名’);
移除类
element.classList.remove(‘类名’);
切换类
element.classList.toggle(‘类名’);
注意:以上所有方法,类名不带点。
返回顶部案例
案例分析:
1、滚动到某个地方显示(使用window.scroll滚动事件,被卷去的头部(window.pageYoffset)大于某个数值时显示)
2、点击返回顶部( window.scroll(0,0) 返回顶部 ),然后返回顶部按钮消失
<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>