如何阻止Div横向滚动及模态框内Canvas签名时禁止页面与模态框滚动
问题1:如何设置Div,使鼠标悬停在该Div上时,其横向滚动(scroll x)无法触发?
要实现鼠标悬停时禁止Div的横向滚动,核心是阻止鼠标滚轮触发横向滚动的默认行为,具体可通过JS监听事件实现:
- 给目标Div绑定鼠标进入/离开事件,进入时添加滚轮事件监听,离开时移除
- 在滚轮事件回调中,判断是否为横向滚动(
deltaX不为0),若是则阻止默认行为
代码示例:
// 替换为你的Div选择器 const targetDiv = document.querySelector('.target-div'); function handleWheel(e) { // 阻止横向滚动 if (e.deltaX !== 0) { e.preventDefault(); } } // 鼠标悬停时添加监听 targetDiv.addEventListener('mouseenter', () => { targetDiv.addEventListener('wheel', handleWheel); }); // 鼠标离开时移除监听 targetDiv.addEventListener('mouseleave', () => { targetDiv.removeEventListener('wheel', handleWheel); });
如果需要兼容触摸设备的横向滑动,可额外添加触摸事件监听:
function handleTouchMove(e) { const touch = e.touches[0]; // 横向滑动时阻止默认行为 if (Math.abs(touch.movementX) > Math.abs(touch.movementY)) { e.preventDefault(); } } targetDiv.addEventListener('mouseenter', () => { targetDiv.addEventListener('wheel', handleWheel); targetDiv.addEventListener('touchmove', handleTouchMove); }); targetDiv.addEventListener('mouseleave', () => { targetDiv.removeEventListener('wheel', handleWheel); targetDiv.removeEventListener('touchmove', handleTouchMove); });
问题2:模态框内Canvas签名时,页面及模态框均不滚动的实现方案
签名时要避免页面和模态框滚动,需在签名操作开始时禁止滚动,结束时恢复,结合CSS和JS即可实现:
样式方案(CSS)
先定义禁止滚动的类:
/* 禁止页面滚动,避免设置overflow:hidden后页面跳顶 */ .body-no-scroll { overflow: hidden; touch-action: none; position: fixed; width: 100%; } /* 禁止模态框滚动 */ .modal-no-scroll { overflow: hidden !important; }
JS逻辑
监听Canvas的鼠标/触摸事件,在签名开始(按下/触摸开始)时给body和模态框添加禁止滚动的类,结束时移除:
const signatureCanvas = document.querySelector('.signature-canvas'); const modal = document.querySelector('.your-modal'); const body = document.body; // 恢复滚动的通用函数 function restoreScroll() { body.classList.remove('body-no-scroll'); modal.classList.remove('modal-no-scroll'); } // 鼠标按下时禁止滚动 signatureCanvas.addEventListener('mousedown', () => { body.classList.add('body-no-scroll'); modal.classList.add('modal-no-scroll'); }); // 鼠标松开或离开Canvas时恢复滚动 signatureCanvas.addEventListener('mouseup', restoreScroll); signatureCanvas.addEventListener('mouseleave', restoreScroll); // 触摸设备适配 signatureCanvas.addEventListener('touchstart', (e) => { // 阻止默认触摸行为,防止滚动触发 e.preventDefault(); body.classList.add('body-no-scroll'); modal.classList.add('modal-no-scroll'); }); signatureCanvas.addEventListener('touchend', restoreScroll); signatureCanvas.addEventListener('touchleave', restoreScroll);
说明:touch-action: none用于解决iOS设备上的滚动穿透问题,position: fixed避免body设置overflow: hidden后页面跳回顶部。
内容的提问来源于stack exchange,提问作者Luis Fernando
相关产品推荐
相关产品推荐

