JavaScript implements the page directory function anchor point jump gesture (operate page element scrolling, and monitor scrolling) record

Javascript implements the page directory function anchor point jump knowledge point summary

False dom A is the box of the scroll bar, B is a sub-element of A, and realizes the method of scrolling B to the top of A's visual range (only record the two methods I used)

1. scrollTo method

Through the scrollTo method of A (the box of the scroll bar), set top to the offsetTop property value of B

scrollTo: The scrollTo() method of Element (the box of the scroll bar) can make the interface scroll to the specified coordinate position of the given element

  A.scrollTo({
    
    
    top: B.offsetTop,
    behavior: 'smooth' // 让滚动又湿又滑
  })

insert image description here

2、scrollIntoView

Make B enter the visual range of A through the scrollIntoView method of B (child element)

scrollIntoView: The scrollIntoView() method of the Element interface will scroll the parent container of the element, making the element called scrollIntoView() visible to the user

  B.scrollIntoView({
    
     block: 'start', behavior: 'smooth' })

Generally, using scrollIntoView can satisfy the function of scrolling the dom to the visible range of the parent container (start at the top, center at the middle, end at the bottom, and nearest) in most cases. However, if you need the dom to scroll to the specified pixel position within the visible range of the parent container, you need to use scrollTo for precise positioning

For example, in the case where there is a child element C in the box A of the scroll bar that is fixedly positioned (or other operations that are out of the document flow) at the top of A, at this time, when operation B scrolls to the top of A's visible range, it will be replaced by C. highly occluded part

Use the scrollTo method to solve: set the top attribute value to B.offsetTop minus the height value of C

  A.scrollTo({
    
    
    top: B.offsetTop - Hc,
    behavior: 'smooth'
  })

insert image description here

Listen to the scroll event of A (the box of the scroll bar)

Listen to the scroll event of A (the box of the scroll bar) Compare the value of e.target.scrollTop with the value of B.offsetTop to determine whether B is within the visible range of A

  A.addEventListener('scroll', function(e){
    
    
    if(Math.abs(B.offsetTop - e.target.scrollTop) < 200){
    
     // 200的范围值根据实际情况而定
     // 操作 
    }
  })

MDN Documentation
Reference Document 1
Reference Document 2

Guess you like

Origin blog.csdn.net/weixin_42508580/article/details/124255747