Hammer.js滑动滚动问题:如何实现每次滑动滚动50%视口高度?
Fix: Repeated 50vh Scrolling on Vertical Swipes
Hey there, let's break down why your vertical swipe only triggers once and fix it to scroll 50vh every time you swipe.
The Root Problem
Your current code uses window.scroll(), which sets an absolute scroll position in the document. For example:
- When swiping up, you’re telling the browser to scroll to exactly
window.innerHeight/2pixels from the top. After the first scroll, that position doesn’t change—so subsequent swipes do nothing (even though the code runs, the page is already where you’re asking it to go). - When swiping down,
window.innerHeight/-2just scrolls to the top every time, which only appears to work once you’re already at the top.
The Solution: Use Relative Scrolling
Instead of setting an absolute position, use window.scrollBy()—this method scrolls relative to the current position, so each swipe adds a 50vh offset to where the page currently is. Here’s your updated code:
// init hammer function var element = document.getElementById('pinwall-grid'); var hammertime = Hammer(element).on("drag", function(event) { direction = event.gesture.direction; if (direction == 'left') { var $meN = $('.pinwall-grid .ctrl a.next'); if (!$meN.hasClass("nextD")) { $meN.trigger('click'); } console.log('left'); } else if (direction == 'right') { var $meP = $('.pinwall-grid .ctrl a.prev'); if (!$meP.hasClass("prevD")) { $meP.trigger('click'); } console.log('right'); } else if (direction == 'up') { // Scroll UP by 50vh (relative to current position) window.scrollBy({ top: -window.innerHeight / 2, left: 0, behavior: 'smooth' }); console.log('up'); } else if (direction == 'down') { // Scroll DOWN by 50vh (relative to current position) window.scrollBy({ top: window.innerHeight / 2, left: 0, behavior: 'smooth' }); console.log('down'); } event.gesture.stopDetect(); });
Key Changes Explained
- Swapped
window.scroll()forwindow.scrollBy(): This ensures each swipe moves the page relative to its current position, not a fixed point. - Adjusted
topvalues: Upward swipes use a negative offset to scroll up, downward swipes use a positive offset to scroll down—both equal to 50vh (window.innerHeight/2). - Fixed console logs: Your original code had mismatched log messages (e.g., logging "down" when swiping up) — this corrects that to match the actual action.
With this change, every vertical swipe will scroll the page 50vh from its current position, and the action will work reliably every time you swipe.
内容的提问来源于stack exchange,提问作者user9769696
相关产品推荐
相关产品推荐

