简体   繁体   中英

Use scrollIntoView on a sticky element

I'm trying to scroll an element that has position sticky to the center of the page.

Meaning that it's non stuck position in the document flow should be in the center of the view.

Demo on codepen

// This code snippet is here because stack overflow doesn't let me post the codepen link without it.
// Using scrollInToView in a stack overflow snippet doesn't work correctly and will just make it more confusing to demo this issue

// Pseudo code
buttonElement.onClick(e =>
  stickyElement.scrollIntoView(options)
)

There are navigation links in the header that scroll to that part of the page using scrollIntoView.

The third section has position sticky.

If it's currently in the document flow (like position static/reletive) it works normally

If it's currently not in the document flow (like position absolute/fixed) it'll behave like so and won't scroll all the way to it. (Like the page title button on the bottom left.)

Is scrollInToView supposed to work on sticky elements, considering that they can be in the document flow at times?

How can I work around this?

Of course, scrollInToView has to work on sticky elements. Because it behave partially like relative (since position with relative response to scrollInToView js) and is always in document flow.

Work around that I found is to add an invisible div element with same id just above the sticky element and remove the id attribute from the same or put value something else as below:

<div id="3" style="height: 0px; opacity: 0;">
</div>
<button id="10" class="sticky">
3.
Lorem Ipsum is simply dummy text of th
</button>

so on....

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