如何使用jQuery上下滚动页面至锚点? [英] How to scroll up or down the page to an anchor using jQuery?
本文介绍了如何使用jQuery上下滚动页面至锚点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种方法,当您单击指向页面上方或下方的本地锚点的链接时,添加一种幻灯片效果.
I'm looking for a way to include a slide effect for when you click a link to a local anchor either up or down the page.
我想在您的链接中添加以下内容:
I'd like something where you have a link like so:
<a href="#nameofdivetc">link text, img etc.</a>
也许添加了一个类,所以您知道希望此链接成为滑动链接:
perhaps with a class added so you know you want this link to be a sliding link:
<a href="#nameofdivetc" class="sliding-link">link text, img etc.</a>
然后,如果单击此链接,页面将向上或向下滑动到所需位置(可以是div,标题,页面顶部等).
Then if this link is clicked, the page slides up or down to the required place (could be a div, heading, top of page etc).
这是我以前的经历:
$(document).ready(function(){
$(".scroll").click(function(event){
//prevent the default action for the click event
event.preventDefault();
//get the full url - like mysitecom/index.htm#home
var full_url = this.href;
//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
var parts = full_url.split("#");
var trgt = parts[1];
//get the top offset of the target anchor
var target_offset = $("#"+trgt).offset();
var target_top = target_offset.top;
//goto that anchor by setting the body scroll top to anchor top
$('html, body').animate({scrollTop:target_top}, 1500, 'easeInSine');
});
});
推荐答案
说明
您可以使用jQuery.offset()
和jQuery.animate()
进行此操作.
Description
You can do this using jQuery.offset()
and jQuery.animate()
.
查看 jsFiddle演示.
function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top},'slow');
}
scrollToAnchor('id3');
更多信息
- jsFiddle演示
- jQuery.offset()
- jQuery.animate()
- jsFiddle Demonstration
- jQuery.offset()
- jQuery.animate()
More Information
这篇关于如何使用jQuery上下滚动页面至锚点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文