移动端web-点击事件active样式
移动端的点击事件不能用click直接来进行,因为click有延迟,所以用touchstart和touchend来实现
需要有三个判断:
① 判断是否是双指操作;
② 判断是不是长按的操作;
③ 判断是不是拖动的操作;
<!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">
<title>移动端-点击事件active样式</title>
<style> ul { list-style: none; padding: 0; margin: 0; } .con { width: 100%; height: 300px; background: yellow; margin: 200px auto; overflow: hidden; } .con ul li { width: 90%; height: 100px; padding: 20px 20px; margin: 0 auto; border-bottom: 1px solid #eee; box-sizing: border-box; /*不将padding值计算到元素中*/ text-align: center; line-height: 100px; background: skyblue; } .active { color: #fff; background: blue!important } </style>
</head>
<body>
<div class="con">
<ul>
<li>第一个</li>
<li class="active">第二个</li>
<li>第三个</li>
</ul>
</div>
<script> let lis = document.querySelectorAll('li'), uls = document.querySelector('ul'); // 或者也可以如下获取ul里面的li元素 // lis = uls.querySelectorAll('li') let startTime, endTime, startY, startX, endX, endY; uls.addEventListener('touchstart', (e)=>{ // 判断是不是双指操作 if (e.targetTouches.length >= 2){ return } startTime = Date.now() startY = e.targetTouches.clientY startX = e.targetTouches.clientX }) uls.addEventListener('touchend', function(e){ // 根据放置的时间判断是点击还是长按 endTime = Date.now() // 前后的时间戳相差 150以上就视为长按 if (endTime - startTime > 150){ return } // 拖动的时候不给点击事件 // 点击滑动的距离超过6就视为滑动而非点击了 endY = e.targetTouches.clientY endX = e.targetTouches.clientX if (endX - startX > 6 || endY - startY > 6){ return } // console.log(e.target.parentNode) 获取该元素上一级的父元素 let num = e.target for (let i = 0; i < lis.length; i++){ // 给新元素添加active之前先把之前的 active清除 lis[i].classList.remove('active') } num.classList.add('active') }) </script>
</body>
</html>
还没有评论,来说两句吧...