当前位置:首页 > JavaScript

js实现上划翻页

2026-02-03 06:03:31JavaScript

监听触摸事件

通过监听 touchstarttouchmovetouchend 事件来捕捉用户滑动行为。记录触摸起始位置和移动距离,判断是否为有效的上滑动作。

let startY = 0;
let endY = 0;

document.addEventListener('touchstart', (e) => {
  startY = e.touches[0].clientY;
});

document.addEventListener('touchmove', (e) => {
  endY = e.touches[0].clientY;
});

判断滑动方向

touchend 事件中计算垂直滑动距离和方向。若滑动距离超过阈值且方向向上,则触发翻页逻辑。

document.addEventListener('touchend', () => {
  const distance = endY - startY;
  const isSwipeUp = distance < -50; // 阈值设为50px

  if (isSwipeUp) {
    goToNextPage();
  }
});

翻页动画效果

使用 CSS 过渡或动画实现平滑的翻页效果。通过添加/移除类名控制页面切换动画。

function goToNextPage() {
  const currentPage = document.querySelector('.page.active');
  const nextPage = document.querySelector('.page:not(.active)');

  currentPage.classList.remove('active');
  nextPage.classList.add('active');
}

CSS 样式示例

为页面容器和动画效果添加基础样式,确保滑动时视觉连贯性。

.page {
  position: absolute;
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease;
}
.page.active {
  transform: translateY(0);
}
.page:not(.active) {
  transform: translateY(100%);
}

边界条件处理

禁止在页面过渡期间重复触发翻页,可通过标志位控制。

let isAnimating = false;

function goToNextPage() {
  if (isAnimating) return;
  isAnimating = true;

  // 翻页逻辑...
  setTimeout(() => {
    isAnimating = false;
  }, 300); // 匹配CSS动画时长
}

多页场景扩展

对于多页场景,可通过数组或自定义属性管理页面索引。

js实现上划翻页

let currentIndex = 0;
const pages = document.querySelectorAll('.page');

function goToNextPage() {
  if (currentIndex >= pages.length - 1) return;

  pages[currentIndex].classList.remove('active');
  currentIndex++;
  pages[currentIndex].classList.add('active');
}

标签: 翻页js
分享给朋友:

相关文章

js实现轮播图

js实现轮播图

轮播图实现方法 基础HTML结构 <div class="slider"> <div class="slides"> <img src="image1.jpg…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…