如何使用 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()
这篇关于如何使用 jQuery 向上或向下滚动页面到锚点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文