在 iPhone 上第一次滑动后滑块停止工作

问题描述 投票:0回答:1

正如标题中提到的,我在 iPhone 上遇到了奇怪的错误,第一次滑动后,滑块停止工作并且不再继续注册滑动,我已经在多个设备和所有 Android 设备上测试了滑块Chrome 中的开发者工具一切正常。

document.addEventListener("DOMContentLoaded", function() {
  const slider = document.querySelector('.slider');
  const prevButton = document.querySelector('.prev-button');
  const nextButton = document.querySelector('.next-button');
  const slides = Array.from(slider.children);
  const slideCount = slides.length;
  let slideIndex = 0;
  let startX = 0;
  let endX = 0;

  prevButton.addEventListener('click', () => {
    slideIndex = (slideIndex - 1 + slideCount) % slideCount;
    slide();
  });

  nextButton.addEventListener('click', () => {
    slideIndex = (slideIndex + 1) % slideCount;
    slide();
  });

  const slide = () => {
    const slideOffset = -slideIndex * slider.clientWidth;
    slider.style.transform = `translateX(${slideOffset}px)`;
  };

  
  slider.addEventListener('touchstart', touchStart);
  slider.addEventListener('touchmove', touchMove);
  slider.addEventListener('touchend', touchEnd);

  function touchStart(e) {
    startX = e.touches[0].clientX;
  }

  function touchMove(e) {
    endX = e.touches[0].clientX;
    
    e.preventDefault();
  }

  function touchEnd() {
    const swipeThreshold = 50; 
    const swipeDistance = startX - endX;

    if (swipeDistance > swipeThreshold) {
      
      slideIndex = (slideIndex + 1) % slideCount;
    } else if (swipeDistance < -swipeThreshold) {
      
      slideIndex = (slideIndex - 1 + slideCount) % slideCount;
    }
    
    slide();
    startX = 0;
    endX = 0;
  }

  window.addEventListener('load', () => {
    slide();
  });
});
javascript iphone web slider
1个回答
0
投票

由于默认事件优先,触摸事件很可能被取消。您可以通过添加

touchcancel
监听器并检查它是否在 iPhone 上触发来测试这一点。

如果是这种情况,您需要将父元素上的

touch-action
CSS 属性设置为预期行为(无论如何,这可能是一个好主意)。如果您自己通过 JS 处理所有触摸操作,那么您可以在父元素上设置
touch-action: none

© www.soinside.com 2019 - 2024. All rights reserved.