简体   繁体   中英

How to scroll down by certain amount of pixels below a container with an id?

I have something like this when an event is triggered:

window.location.href = "#my-elm";

And I have a div that has that id, when the event is triggered my window is scolling to the div position of course, but I have a fixed header on top in the page of about 150px in height, so part of my div is not visible..

What I want to do is when my event is triggered I will scroll down to the anchor position + 150 px

I tried to add this on my page, what I understand is this is going to watch my hash haching ( my anchors changing?? ), & this will scroll an extra 150 px, but did not work

window.addEventListener("hashchange", function () {
    window.scrollTo(window.scrollX, window.scrollY + 150);
});

Any ideas?

Any help would be much appreciated.

EDIT:

The answer provided is correct for Firefox, Edge, Chrome, Opera, Safari +11

For Safari -11 this won't work, it will work only for the latest versions, which is bad, you have to implement an other solution to fix the Safari BUG

It can be done with CSS only.

Add a scroll-margin-top to the :target selector like this:

:target {
 scroll-margin-top: 150px;
}

It will add a margin from the top edge of the scroll container for every anchor element, if you want to apply it just for #my-elm for some reason, change the selector from :target to #my-elm

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