iOS 10 Safari: Prevent scrolling behind a fixed overlay and maintain scroll position

前端 未结 10 2176
我寻月下人不归
我寻月下人不归 2020-12-12 13:51

I\'m not able to prevent the main body content from scrolling while a fixed position overlay is showing. Similar questions have been asked many times, but all of the techniq

10条回答
  •  孤城傲影
    2020-12-12 14:31

    For those using React, I've had success putting @bohdan-didukh's solution in the componentDidMount method in a component. Something like this (link viewable via mobile browsers):

    class Hello extends React.Component {
      componentDidMount = () => {
        var _overlay = document.getElementById('overlay');
        var _clientY = null; // remember Y position on touch start
    
        function isOverlayTotallyScrolled() {
            // https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions
            return _overlay.scrollHeight - _overlay.scrollTop <= _overlay.clientHeight;
        }
    
        function disableRubberBand(event) {
            var clientY = event.targetTouches[0].clientY - _clientY;
    
            if (_overlay.scrollTop === 0 && clientY > 0) {
                // element is at the top of its scroll
                event.preventDefault();
            }
    
            if (isOverlayTotallyScrolled() && clientY < 0) {
                //element is at the top of its scroll
                event.preventDefault();
            }
        }
    
        _overlay.addEventListener('touchstart', function (event) {
            if (event.targetTouches.length === 1) {
                // detect single touch
                _clientY = event.targetTouches[0].clientY;
            }
        }, false);
    
        _overlay.addEventListener('touchmove', function (event) {
            if (event.targetTouches.length === 1) {
                // detect single touch
                disableRubberBand(event);
            }
        }, false);
      }
    
      render() {
        // border and padding just to illustrate outer scrolling disabled 
        // when scrolling in overlay, and enabled when scrolling in outer
        // area
        return 
    {[...Array(10).keys()].map(x =>

    Text

    )}
    ; } } ReactDOM.render( , document.getElementById('container') );

    Viewable via mobile: https://jsbin.com/wiholabuka

    Editable link: https://jsbin.com/wiholabuka/edit?html,js,output

提交回复
热议问题