Ok, I have a few issues... I'm building my site with bootstrap/jquery. I'm using bootstrap nav and all nav links are hash links to different containers on the same page.
Issue #1 When using the method below to 'hijack' the link I lose the URL address thus look the ability for people to grab the link and share or link to it later.
Issue #2 There are a few other pages with content that aren't on the homepage. So obviously when users click on the link /somepage/#photography doesn't work. Is the only solution here to not use relative links?
<nav>
<a href="#photography">Photography</a>
</nav>
// smooth scroll from navigation
$('nav a').click(function(evt){
evt.preventDefault();
var $section = $($(this).attr('href'));
scrollToObject($section);
});
答案 0 :(得分:1)
问题1:在网址末尾丢失哈希的原因是因为对evt.preventDefault()
的调用阻止了哈希的添加。
我对scrollToObject()
中滚动效果的内部工作方式并不是100%肯定,但如果您在滚动完成时可以提供回调函数,则可以添加location.assign( evt.target.hash );
,这将添加URL (and it will show up in the user's history.) 的哈希值当然,您可以从锚点对象,事件等中获取哈希值。
您可以在此处阅读MDN上js中的位置界面:https://developer.mozilla.org/en-US/docs/Web/API/Location
问题2:您可以使用location.assign()
再次实现此目的。再一次,在没有看到所有代码的情况下,您可以在回调中创建条件,然后使用滚动锚点将用户发送回页面:location.assign( location.origin + '/' + evt.target.hash )
。