简体   繁体   中英

remove hash location from history and browsers back button

i have a project in which i have to scroll to a particular image out of a list of them. those images are lazy loaded (since they are all high resolution).

my current approach is to have an internal link to each one of them:

<a name="photo1"><img ... /></a>

when i click on a thumbnail to see the original photo i get a click by doing:

location.hash = "#photo1"

the problem is when i click browser back and forward, the page does not go back to the prev page, instead goes back to whatever photo link has been clicked previously

how can i remove all hash from history?

Your best bet here, I think, is to manually scroll to a target element with JavaScript.

Use the native scrollIntoView to jump to your element:

document.getElementById('[id]').scrollIntoView(true);

You can actually execute this in the <a> href attribute.

<a href="javascript:document.getElementById('[id]').scrollIntoView(true);">

Then, if you desire, you can manually add in the hash without adding a new history entry.

window.location.replace("#[id]");

Sources:

Making browsers ignore the URL hash when the back button is clicked

Scroll with anchor without # in URL

How to call JavaScript function instead of href in HTML

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