如何使用jQuery向上或向下滚动页面到锚点?

前端之家收集整理的这篇文章主要介绍了如何使用jQuery向上或向下滚动页面到锚点?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一种方法来包含一个幻灯片效果,当你点击页面上或下的本地锚点链接时。

我想要一个你有这样一个链接的东西:

  1. <a href="#nameofdivetc">link text,img etc.</a>

也许添加了一个类,所以你知道你希望这个链接是一个滑动链接

  1. <a href="#nameofdivetc" class="sliding-link">link text,img etc.</a>

然后,如果单击此链接页面将向上或向下滑动到所需位置(可以是div,标题页面顶部等)。

这就是我以前的情况:

  1. $(document).ready(function(){
  2. $(".scroll").click(function(event){
  3. //prevent the default action for the click event
  4. event.preventDefault();
  5.  
  6. //get the full url - like mysitecom/index.htm#home
  7. var full_url = this.href;
  8.  
  9. //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
  10. var parts = full_url.split("#");
  11. var trgt = parts[1];
  12.  
  13. //get the top offset of the target anchor
  14. var target_offset = $("#"+trgt).offset();
  15. var target_top = target_offset.top;
  16.  
  17. //goto that anchor by setting the body scroll top to anchor top
  18. $('html,body').animate({scrollTop:target_top},1500,'easeInSine');
  19. });
  20. });

解决方法

描述

您可以使用jQuery.offset()和jQuery.animate()来完成此操作。

查看jsFiddle Demonstration

样品

  1. function scrollToAnchor(aid){
  2. var aTag = $("a[name='"+ aid +"']");
  3. $('html,body').animate({scrollTop: aTag.offset().top},'slow');
  4. }
  5.  
  6. scrollToAnchor('id3');

更多信息

> jsFiddle Demonstration
> jQuery.offset()
> jQuery.animate()

猜你在找的jQuery相关文章