【问题标题】:prevent mouse wheel scroll the web page防止鼠标滚轮滚动网页
【发布时间】:2022-11-12 16:51:49
【问题描述】:

我有一个带有画布的网页,它用于使用 threejs 渲染 3D 场景,但是画布不是全屏的,所以它有滚动条,因为它有一些 HTML 内容。如何防止鼠标滚轮滚动页面并只处理画布内的鼠标滚轮?

我已经为画布添加了 preventDefault 和 stopPropagation on 'wheel' 事件,但页面仍然滚动。

    canvas.addEventListener( 'wheel', onMouseWheel, false );
    function onMouseWheel( event ) {
        event.preventDefault();
        event.stopPropagation();
    }

我在这里还缺少什么?

【问题讨论】:

  • 请不要削弱浏览器。

标签: javascript


【解决方案1】:

你可以使用 css,并使用

body{
    overflow: none;
}

所以页面的其余部分将不可见,滚动条将被隐藏。

【讨论】:

    【解决方案2】:

    对于这种情况,您将有多种解决方案。一种是使用z-index: -1

    canvas.addEventListener( 'wheel', onMouseWheel, false );
    
    function onMouseWheel( event ) {
        event.preventDefault();
        event.stopPropagation();
    }
    div {
      heught:100vh;
      display:flex;
      flex-direction: column;
    }
    canvas {
      background-color: yellow;
      height:200px;
      z-index:-1;
    }
    section {
      background-color: lightgreen;
      height:400px;
    }
    <div>
      <section>A</section>
    
        <canvas id="canvas">Canvas</canvas>
    
      <section>B</section>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多