你应该先解决了你的锚和使用哈希代码段,允许本地导航在锚点之间。
我已经创建了一个非常简单的演示,以便您理解这一点(不使用标记来简化它)。
演示:http://jsfiddle.net/abhitalks/9uxGq/15/
(与你的标记另一个演示:http://jsfiddle.net/abhitalks/9uxGq/19/)
你需要两个锚,一个是点击链接和其他标记目标的锚位置。
例如:
<div>
<a id="LearnMore1"></a> <!-- Used for marking the anchor with hash fragment -->
<h2>Sub Heading 2</h2>
<p>
Some text content here
</p>
<a href="#LearnMore2">Learn More</a> <!-- Used to click to got to next anchor -->
</div>
注:当然不是使用第二锚的标记,你可以用一个id
使用div
(或你的情况section
)。但是,a
更好,因为它对于内容导航更具语义,并且它意味着定位点。
一旦完成,这将成为你的后备。现在,您可以使用轻松实现动画的jQuery等
这将是如此简单:
// bind click on anchors (use selectors as per your requirements)
$("a").on("click", function(e) {
e.preventDefault(); // prevent the default behaviour
var nextAnchor = this.hash.replace("#", ""); // get the next marker anchor
var gotoPoint = $("#" + nextAnchor).position().top; // get the position of marker
$('body').animate({ scrollTop: gotoPoint }, 'normal'); // animate the body
});
或者:
// bind click on anchors (use selectors as per your requirements)
$("a").on("click", function(e) {
e.preventDefault(); // prevent the default behaviour
var nextAnchor = $(this).attr('href'); // get the next marker anchor
var gotoPoint = $(nextAnchor).position().top; // get the position of marker
$('body').animate({ scrollTop: gotoPoint }, 'normal'); // animate the body
});
现在将其应用到您的使用案例,演示变为: http://jsfiddle.net/abhitalks/9uxGq/19/
希望对您有所帮助s,你可以在你的标记和用例中解决它。 。
你期待它的行为如此http://jsfiddle.net/niranjan_borawake/9uxGq/11/? –
部分应该在点击时移动到页面的顶部,还是应该滚动到视图端口的顶部? –
为什么你需要jQuery?在你的url中使用锚点标签名称来指出特定的部分。 –