CSS设置overflow:scroll无法为canvas或容器div启用滚动条求助
问题根因
- 全局
document.ontouchmove事件中调用了e.preventDefault(),直接拦截了所有页面默认触摸滚动行为 - 外层容器
.container没有设置固定高度,overflow: scroll生效的前提是容器高度小于内部内容高度,当前容器高度会被canvas自动撑开,所以滚动条不会触发 - 绘图逻辑中没有做模式判断,所有触摸滑动操作都被canvas的
preventDefault()拦截,无法触发滚动
修复方案
- 给外层容器设置固定高度,让
overflow属性生效 - 新增模式切换状态,区分「绘图模式」和「滚动模式」
- 移除全局的触摸事件拦截,仅在绘图模式下拦截canvas区域的触摸默认行为
- 新增模式切换按钮,供用户切换两种操作状态
完整修改后代码
HTML部分
<!DOCTYPE html> <html> <head> <meta name="viewport" content="user-scalable=no,initial-scale=1.0,maximum-scale=1.0" /> <style> .container { margin: 10px; /* 给容器设置固定高度,这里用90vh适配移动端视口,也可以改成固定像素比如600px */ height: 90vh; overflow: auto; } #main {border: 1px solid #0000ff;} </style> <script src="draw.js"></script> </head> <body> <div class="container"> <button id="clear">清除画布</button> <!-- 新增模式切换按钮 --> <button id="toggleMode">切换为滚动模式</button><br> <canvas id="main" width="250" height="1000"></canvas> </div> </body> </html>
JavaScript部分
window.onload = function() { var canvas = document.querySelector('#main'); var canvastop = canvas.offsetTop; var context = canvas.getContext("2d"); // 新增模式状态,默认是绘图模式 var isDrawMode = true; var toggleBtn = document.getElementById('toggleMode'); var lastx, lasty; context.strokeStyle = "#000000"; context.lineCap = 'round'; context.lineJoin = 'round'; context.lineWidth = 5; function clear() { context.fillStyle = "#ffffff"; context.rect(0, 0, canvas.width, canvas.height); context.fill(); } function dot(x,y) { context.beginPath(); context.fillStyle = "#000000"; context.arc(x,y,1,0,Math.PI*2,true); context.fill(); context.stroke(); context.closePath(); } function line(fromx,fromy, tox,toy) { context.beginPath(); context.moveTo(fromx, fromy); context.lineTo(tox, toy); context.stroke(); context.closePath(); } // 模式切换逻辑 toggleBtn.onclick = function() { isDrawMode = !isDrawMode; toggleBtn.innerText = isDrawMode ? '切换为滚动模式' : '切换为绘图模式'; } canvas.ontouchstart = function(event){ // 只有绘图模式才拦截默认行为,执行绘图逻辑 if (!isDrawMode) return; event.preventDefault(); lastx = event.touches[0].clientX; lasty = event.touches[0].clientY - canvastop; dot(lastx,lasty); } canvas.ontouchmove = function(event){ if (!isDrawMode) return; event.preventDefault(); var newx = event.touches[0].clientX; var newy = event.touches[0].clientY - canvastop; line(lastx,lasty, newx,newy); lastx = newx; lasty = newy; } var clearButton = document.getElementById('clear') clearButton.onclick = clear clear() }
内容的提问来源于stack exchange,提问作者mangadrawing.123
相关产品推荐
相关产品推荐

