Disable scrolling in all mobile devices

后端 未结 13 1076
粉色の甜心
粉色の甜心 2020-11-28 03:18

This sounds like there should be a solution for it all over the internet, but I am not sure why I cannot find it. I want to disable Horizontal scrolling on mobile devices. B

相关标签:
13条回答
  • 2020-11-28 04:12

    Setting position to relative does not work for me. It only works if I set the position of body to fixed:

    document.body.style.position = "fixed";
    document.body.style.overflowY = "hidden";
    document.body.addEventListener('touchstart', function(e){ e.preventDefault()});
    
    0 讨论(0)
  • 2020-11-28 04:13

    This prevents scrolling on mobile devices but not the single click/tap.

    document.body.addEventListener('touchstart', function(e){ e.preventDefault(); });
    
    0 讨论(0)
  • 2020-11-28 04:14

    Try adding

    html {
      overflow-x: hidden;
    }
    

    as well as

    body {
      overflow-x: hidden;
    }
    
    0 讨论(0)
  • 2020-11-28 04:16

    For future generations:

    To prevent scrolling but keep the contextmenu, try

    document.body.addEventListener('touchmove', function(e){ e.preventDefault(); });
    

    It still prevents way more than some might like, but for most browsers the only default behaviour prevented should be scrolling.

    For a more sophisticated solution that allows for scrollable elements within the nonscrollable body and prevents rubberband, have a look at my answer over here:

    https://stackoverflow.com/a/20250111/1431156

    0 讨论(0)
  • 2020-11-28 04:16

    The CSS property touch-action may get you what you are looking for, though it may not work in all your target browsers.

    html, body {
        width: 100%; height: 100%;
        overflow: hidden;
        touch-action: none;
    }
    
    0 讨论(0)
  • 2020-11-28 04:20

    cgvector answer didn't work for me, but this did:

    document.body.addEventListener('touchstart', function(e){ e.preventDefault(); });
    

    I wouldn't leave it just like that, a smarter logic is needed to select when to prevent the scrolling, but this is a good start.

    Taken from here: Disable scrolling in an iPhone web application?

    0 讨论(0)
提交回复
热议问题