简体   繁体   English

禁用锚标签

[英]disable anchor tag

How would I go about putting a link on a page that changes the url, but doesn't change the page without using hash states? 我该如何将链接放在页面上以更改url,但不使用哈希状态就不能更改页面?

I want to put links that change the url and scroll to a corresponding section of the page. 我想放置更改URL的链接并滚动到页面的相应部分。 I don't want to use hashes as they just jump to the section instead of scrolling, and I think hashes dont look very good in the url. 我不想使用哈希,因为它们只是跳转到该部分而不是滚动,而且我认为哈希在url中看起来不是很好。

Take a look at HTML5 Push State 看看HTML5推送状态

There is no other way as far as I know. 据我所知,没有其他办法。

Have you tried the jQuery ScrollTo plugin? 您是否尝试过jQuery ScrollTo插件? http://archive.plugins.jquery.com/project/ScrollTo http://archive.plugins.jquery.com/project/ScrollTo

Browsers now have security features that ensure that the URL displayed in the location bar matches what's actually being displayed. 浏览器现在具有安全功能,可确保在位置栏中显示的URL与实际显示的URL匹配。 You can't change the location without changing the page at the same time. 您不能在不同时更改页面的情况下更改位置。

However, you can scroll the page anywhere you like without changing the URL. 但是,您可以在不更改URL的情况下在任意位置滚动页面。 To scroll to a particular element, get its position and use .animate() : 要滚动到特定元素,请获取其位置并使用.animate()

$('body').animate({scrollTop: $('#element').position().top});

​ Combine this with an .on('click',...) handler that uses e.preventDefault() to cancel the URL change and you're good to go. 与此相结合.on('click',...)使用处理器e.preventDefault()取消URL变化,你是好去。

$('a[href^=#]').on('click', function(e) { // apply to all hash links
    var el = $(this).attr('href');        // get the href
    e.preventDefault();                   // cancel default click action
    $('body').animate({
        scrollTop: $(el).position().top   // scroll to the href ID instead
    });
});​

http://jsfiddle.net/mblase75/WFKUE/ http://jsfiddle.net/mblase75/WFKUE/

HTML5 browser history (aka PushState) is the modern approach HTML5浏览器历史记录(又称PushState)是现代方法

https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history https://developer.mozilla.org/zh-CN/docs/DOM/Manipulating_the_browser_history

It is fairly widely supported in browsers 它在浏览器中得到了广泛的支持

http://caniuse.com/history http://caniuse.com/history

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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