Are there many friends still troubled by this problem? Today, I would like to share my solution to this problem in my project. Countdown 3,2,1 to business:

Principle: The use of CSS overFlow: hidden ideas through JS code. If you simply use this property, the page will roll back to the top, resulting in a bad user experience, as shown in the following code:

  • Get the browser scroll bar width:
getScrollbarWidth () {
    let oP = document.createElement('p')
    let styles = {
      width: '1000px',
      height: '1000px',
      overflowY: 'scroll'
    }
    let i = 0
    let scrollbarWidth = 0
    for (i in styles) {
      oP.style[i] = styles[i]
    }
    document.body.appendChild(oP)
    scrollbarWidth = oP.offsetWidth - oP.clientWidth
    oP.remove()
    return scrollbarWidth
  }
Copy the code
  • Prevents page scrolling event definitions
 stopScroll () {
    let mo = function (e) {
      e.preventDefault()
      e.stopPropagation()
    }
    let _width = this.getScrollbarWidth()
    document.body.style.overflow = 'hidden'
    document.body.style.paddingRight = _width + 'px'
    document.addEventListener('touchmove', mo, false)}Copy the code
  • Resume the page scroll event
 moveScroll () {
    let mo = function (e) {
      e.preventDefault()
      e.stopPropagation()
    }
    document.body.style.overflow = ' '
    document.body.style.paddingRight = 0
    document.removeEventListener('touchmove', mo, false)}Copy the code

Call stopScroll where you need to use, remember to restore the page scroll event moveScroll after the call, here to obtain the width of the browser scroll bar is mainly to optimize the page flashing effect

In the future, I will continue to update the solutions to some problems encountered in the project. I hope to learn and make progress together with you here. I hope to provide more and better solutions