简体   繁体   中英

Scroll to a specific location using only Javascript when scrollTop() is not working?

So my problem is a bit specific.

The first thing is that due to something (I don't know what) the result of any element of the page .scrollTop equal 0

This makes the use of scrollTop() impossible.

However I can use scrollIntoView() BUT I need to add a specific height to my element.

Something like document.getElementById(ELEMENT).scrollIntoView() + 50px .

So I wanted to know what does scrollIntoView() takes in account (since its not scrollTop) and if I could edit this value to manage what I want?

Or maybe you do have an other solution for me?

Edit: This is the page I'm trying to scroll in https://www.naissance.fr/prenoms/ and this is the bloc I want to scroll to (without the navigator over it) : document.getElementsByClassName('mastcontainer__body')[0].scrollIntoView(true);

I guess this is what you have been looking for,

To get the position of any element in page, you can use 'getBoundingClientRect' method like this, and window.scrollTo() to scroll to that particular location.

     var htmlElement = document.getElementById('container');
     var elementPosition = element.getBoundingClientRect()
     window.scrollTo(elementPosition.top, elementPosition.left)

Also refer this link for more learning: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM