Disable the overall scrolling of the page caused by mouse scrolling in a specific area

Today I received a bug fix request: when the user continues to scroll the mouse at the bottom of the left menu bar, the main content on the right scrolls, which should be prohibited, that is, the scrolling of the menu bar should not affect the main content on the right.

Get into the habit of writing together! This is the 4th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the event details .

After some research and data searching, I came up with two solutions:

  • When the mouse enters the bottom area on the left, the scroll bar of the main content container is hidden, and the scroll bar is hidden, and naturally it cannot be scrolled.
  • Add scroll listener events to the bottom left area to prevent the default behavior (that is, the behavior of triggering and propagating page scrolling)

hide scrollbar

To hide the scrollbar of an element we need the following style:

.container.disable-scrollbar {
  /* hide scrollbar in firefox */
  scrollbar-width: none;
}
.container.disable-scrollbar::-webkit-scrollbar {
  display: none;
}
复制代码

We need to hide the scroll bar when the mouse enters the left bottom area, and unhide when the mouse moves out of the left bottom area. It is not hidden by default:

const bottomEleContainer = ...
const mainEleContainer = ....
bottomEleContainer.addEventListener('mouseenter',()=>{
    //激活上述样式
    mainEleContainer.className = 'disable-scrollbar'
})
bottomEleContainer.addEventListener('mouseleave',()=>{
    //取消激活上述样式
    mainEleContainer.className = ''
})
复制代码

Prevent the default behavior of the mouse wheel

Here we need to add a mouse wheel event listener to the element:

bottomEleContainer.addEventListener('wheel', (e)=>{
  //阻止默认行为(页面的滚动行为)
  e.preventDefault()
},{
  //这里一定要显式设置为false,因为默认是true
  passive: false,
})
复制代码

If you use the method that Reactshould avoid the direct onWheelway of listening on the node, but useRefobtain the application of the DOM node through a hook-like method, and then use the above-mentioned native method to listen. Remember to return the removal code of the event listener in the hook.

Summarize

The disadvantages of the first one are more obvious:

  • extra css code (including compatibility code)
  • The switching of the scroll bar visibility will lead to changes in the size of the content box on the page, and the change in the size of the content box will cause the page to be rearranged.
  • There is a certain coupling, once the main page container is changed and not synchronized in time, the code will fail

Let's look at the second one. It does not have the above shortcomings and is simpler. I decided to choose the second one.

Guess you like

Origin juejin.im/post/7085915795892469774