双击回到顶部
左滑动
右滑动
代码展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Gesture Example</title>
<style>
body {
margin: 0;
height: 200vh;
} /* 模拟长页面 */
.notification {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
font-size: 24px;
border-radius: 10px;
opacity: 0;
transition: opacity 0.5s ease, transform 0.5s ease;
}
.notification.show {
opacity: 1;
transform: translate(-50%, -50%) scale(1.1);
}
</style>
</head>
<body>
<div class="notification" id="notification"></div>
<div style="height: 30vh; background-color: rgb(178, 129, 129)"></div>
<div style="height: 30vh; background-color: rgb(141, 40, 40)"></div>
<div style="height: 30vh; background-color: rgb(135, 85, 85)"></div>
<div style="height: 30vh; background-color: rgb(209, 188, 188)"></div>
<div style="height: 30vh; background-color: rgb(203, 44, 44)"></div>
<script>
//在dom完全加载后执行
document.addEventListener("DOMContentLoaded", () => {
let touchStartX = 0;
let touchStartY = 0;
let touchEndX = 0;
let touchEndY = 0;
let lastTap = 0;
const notification = document.getElementById("notification");
//监听开始事件
document.addEventListener("touchstart", (e) => {
touchStartX = e.changedTouches[0].screenX;
touchStartY = e.changedTouches[0].screenY;
});
//监听移动事件
document.addEventListener("touchmove", (e) => {
touchEndX = e.changedTouches[0].screenX;
touchEndY = e.changedTouches[0].screenY;
});
//监听结束事件
document.addEventListener("touchend", () => {
handleGesture();
});
//监听双击事件
document.addEventListener("touchend", (e) => {
const currentTime = new Date().getTime();
const tapLength = currentTime - lastTap;
if (tapLength < 300 && tapLength > 0) {
// 双击事件
window.scrollTo({ top: 0, behavior: "smooth" });
}
lastTap = currentTime;
});
//判断手势
function handleGesture() {
const deltaX = touchEndX - touchStartX;
const deltaY = touchEndY - touchStartY;
if (Math.abs(deltaX) > Math.abs(deltaY)) {
if (deltaX > 50) {
showNotification("右滑动");
} else if (deltaX < -50) {
showNotification("左滑动");
}
}
}
//显示通知
function showNotification(message) {
notification.textContent = message;
notification.classList.add("show");
setTimeout(() => {
notification.classList.remove("show");
}, 1000);
}
});
</script>
</body>
</html>