The scrollIntoView() positioning element display causes the page to move up the solution?


Project scenario:

In the project, it is necessary to locate and display at the top of the page according to the componentId of the current component.


Problem Description

I originally wanted to use the most traditional method, according to the height of the parent box and the height of the child box...etc. Later, I found out that it has something to do with the page layout. Using this method will lead to inaccurate jumps. The first click can be used for the second time. , and then tried again and again..., and then I figured it out scrollIntoView().


Some friends may ask: "Why not scrollTo?" In fact, I also think about it, but the parent box is not the outermost one, and it scrollTocan only be called by windowcalling, that is, it can only control the scrolling of the outermost box.


But the gods just don’t care about me as a hard worker, it’s okay to jump to Mad, and then the tabs page is shifted up a little...

I am so hard...


Cause Analysis:

hint:原因不道!就很奇妙


solution:

1. Use fixed to fix the parent element

Note:
The fixed positioning box here is the parent of the scrolling element (that is, the box with the scroll bar)


<style>
	/* 解决父级盒子向上偏移 */
	parentBox {
      
      
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
	}
</style>

2. Control the scrollTop of the parent element

Abandon scrollIntoView()the method to achieve positioning according to the scroll top value of the control parent element.
This method is the best, because scrollIntoView()the method will have compatibility issues, such as silky scrolling, which is compatible with the three browsers of Google, Firefox and Microsoft.

function jump(id){
    
    
	const comDom = document.getElementById('' + id + ''); //当前要定位的DOM元素
	const offsetTop = comDom?.offsetTop - 5; //元素距离外部盒子顶部的高度(-5是为避免被覆盖物遮挡)
	const scrollTopDom = document.getElementsByClassName('van-tabs__content')[0] || {
    
    }; // 滚动元素的父级
	scrollTopDom.scrollTop = offsetTop; // 设置父元素的滚动条位置
	console.log('----------跳转成功----------')}

The above-5 can refer to this article to avoid occlusion of fixed covering elements

At present, it is just a simple jump. To achieve automatic scrolling, we need to add it to the scrolling box scroll-behavior: smooth;, so that a silky automatic jump can be achieved!

Note:
offsetTop It is not necessarily relative to the parent element. If there are many parent elements, it is relative to the first positioned parent element.
If the first parent element is not positioned (relative, absolute or fixed), you may need to change the second line to:
父级元素.scrollTop = 当前元素,offsetTop - 父级元素.offsetTop;


Guess you like

Origin blog.csdn.net/weixin_61102579/article/details/131910612