[英]How can I implement links within a page, while using Client-side routing?
I'm working on an SPA, using crossroads.js for the client-side routing. 我正在使用crossroads.js进行客户端路由的SPA。 Everything is working perfectly, with one exception. 除了一个例外,一切都工作正常。
I have one page within this SPA that is quite large, and I'd like to be able to use internal links, to provide a table of contents at the top. 我在此SPA中有一个很大的页面,并且我希望能够使用内部链接在顶部提供一个目录。 In the past, I've done something like this: 过去,我做过这样的事情:
<ul>
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Chap1">Chapter 1</a></li>
<li><a href="#Chap2">Chapter 2</a></li>
<li><a href="#Chap3">Chapter 3</a></li>
</ul>
These would link to elements within the same page with the corresponding ID. 这些将链接到同一页面中具有相应ID的元素。
However, now that I'm using client-side routing, this doesn't seem work work as well. 但是,由于我正在使用客户端路由,因此似乎也无法正常工作。 The page that this I'm using this on has a URL like: 我正在使用此页面的页面具有如下网址:
http://myserver.com/#/Books/12/Full
Clicking one of the links above does move the page to the correct location on screen, but it changes the URL to: 单击上面的链接之一不会将页面移至屏幕上的正确位置,但会将URL更改为:
http://myserver.com/#Chap2
Is there a standard way of handling internal links in an SPA, while preserving the URL? 在保留URL的同时,是否存在处理SPA中内部链接的标准方法?
<nav>
<ul>
<li data-rel="div1">DIV 1</li>
<li data-rel="div2">DIV 2</li>
<li data-rel="div3">DIV 3</li>
</ul>
</nav>
<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>
$(function() {
$('nav ul li').click(function() {
$('html, body').animate({ scrollTop: $('#'+$(this).data('rel')).offset().top }, 900);
});
});
@mdesdev got me pointed in the right direction, but here's what ultimately wound up working for me: @mdesdev让我指出了正确的方向,但这最终为我工作了:
Using an SPA, the page in question is loaded after the document is loading, so I couldn't get using the jQuery document ready function to add the click handler to work. 使用SPA,有问题的页面会在文档加载后加载,因此我无法使用jQuery文档就绪功能来添加点击处理程序。 Instead, I created the following function: 相反,我创建了以下函数:
function scrollToInternal(target) {
// #MyContent is the div that needs to be scrolled
$('#MyContent').scrollTop($(target).position().top);
};
Then in my markup, I called this function with the onclick attribute: 然后在标记中,我使用onclick属性调用了此函数:
<ul>
<li><a href="#" onclick="scrollToInternal('#Introduction');return false">Introduction</a></li>
<li><a href="#" onclick="scrollToInternal('#Chap1');return false">Chapter 1</a></li>
<li><a href="#" onclick="scrollToInternal('#Chap2');return false">Chapter 2</a></li>
<li><a href="#" onclick="scrollToInternal('#Chap3');return false">Chapter 3</a></li>
</ul>
Not as elegant a solution as mdesdev's, but it's working. 没有mdesdev的解决方案那么优雅,但是它正在工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.