Remove hashtags from a URL but still jump to the element

北城余情 提交于 2019-12-11 11:43:11

问题


Here's my predicament. I have three links from one page that go to another one and take the visitor to its respective DIV id:

www.mysite.com/#about
www.mysite.com/#gallery
www.mysite.com/#help

It's working fine, but I really need to remove the trailing hashtags from the URL or it messes with a jquery gallery slider. Is this possible? I've seen others asking similar questions but they don't seem to be navigating to a new page.

What I am looking for is a way for a visitor to click on the link (e.g., www.mysite.com/#about) and be taken to that page (and respective element) but have the browser trim off the #about and just report www.mysite.com.

Jquery, PHP, javascript, I don't care what really.

I was thinking another alternative would be to take the user to www.mysite.com and then apply the hashtag afterwards. Is this at all possible? Just so they are taken to the element but the url in the browser doesn't reflect the hashtag.

PS: I'm no coder so if there is a bit of code that can do this, can you guys be really clear on how to implement?

Many thanks.


回答1:


We can use the history api.

First, we check if there's a state in the stack. Whatever the state is will be the most recent item we pushed into the stack.

We assume that the id of the element is the same as the hash. We use it as a selector on our div and get that divs offset().top.

if(history.state){  
    $('html, body').scrollTop($('div[id='+history.state.element+']').offset().top); 
}

Now let's take a look at the click function. We prevent the default behavior and store the href in a variable (because we'll use it a few times). We push a state into the stack. The element key has a value of whatever comes after the hash tag. We also provide some other information about the stacked state. When we're done, we simply redirect the page location to the element's location without the hash tag.

$('a').on('click', function(e){
    e.preventDefault();

    var ele =  $(this).prop('href');
    window.history.pushState({'element' : ele.split('#')[1]}, ele, ele.split('#')[0]);

    window.location = ele.split('#')[0]; 
});

Now when the next page loads, the history wlil have a state, which will be the most recent stack pushed. This will emulate the behavior you desire.




回答2:


This is a nice solution in jQuery:

http://demos.flesler.com/jquery/scrollTo/



来源:https://stackoverflow.com/questions/14120053/remove-hashtags-from-a-url-but-still-jump-to-the-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!