开发需求时,遇到如下场景:
h5页面使用swiper库实现拖动幻灯片功能,页面是iframe内嵌至父窗口,鼠标点击卡片拖拽滑动时,若鼠标滑出iframe窗口,会出现卡片卡顿住,此时松开鼠标,无论鼠标是否在iframe窗口内,卡片都不会复位,需要重新点击iframe窗口才会复位
猜想出现这个问题大概率是swiper没有对多document下的边界做处理,github上搜了下发现有人提出了相同问题
通过查看swiper库源码,发现确实没有做类型行为的处理,解决思路是:
监听鼠标移出iframe事件,如果鼠标移出了iframe,那么模拟松开鼠标事件,触发swiper正常滑动,通过源码最终定位到swiper内部是通过监听当前document的pointerup事件触发轮播,因此,只需要在鼠标移动出iframe时,分发一下pointerup事件,便能实现想要的效果
代码:
function addScrollListen() {
document.addEventListener(‘mouseleave’, _dealScrollOut)
}
function removeScrollListen() {
document.removeEventListener(‘mouseleave’, _dealScrollOut)
}
function _dealScrollOut() {
const pointerup = new PointerEvent(‘pointerup’, {
bubbles: true,
cancelable: true,
pointerId: 1,
pointerType: ‘mouse’,
})
document.dispatchEvent(pointerup)
removeScrollListen()
}
const _swiperRef = useRef()
<Swiper
centeredSlides={true}
onSwiper={swiper => {
_swiperRef.current = swiper
}}
onTouchStart={() => {
addScrollListen()
}}
>