当前位置:首页 > 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 事件中计算垂直滑动距离和方向。若滑动距离超过阈值且方向向上,则触发翻页逻辑。

js实现上划翻页

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 样式示例

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

js实现上划翻页

.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动画时长
}

多页场景扩展

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

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
分享给朋友:

相关文章

vue实现翻页效果

vue实现翻页效果

Vue实现翻页效果的方法 使用v-for和计算属性 通过计算属性动态计算当前页显示的数据,结合v-for渲染分页内容。定义currentPage和pageSize控制分页逻辑。 <templ…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 //…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https:/…

js实现拖拽

js实现拖拽

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

js实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以直…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…