2012-02-19 179 views
5

我在其他網站上看到了這個非常酷的功能,但我似乎無法自己找到它。減慢html錨鏈接

我想通過錨標記滾動來鏈接到頁面的不同部分,而不是隻跳轉到所需的ID。我想一個JavaScript文件可以幫助或者可能是一個CSS轉換,但我不知道這將是過渡元素。

<a href="#bottom">scroll to bottom</a> 

<p id="bottom">bottom</p> 

謝謝:)

+0

我好嵌入的代碼,我不能改變它......但我確定你明白我的意思。 – 2012-02-19 04:38:45

+0

[jQuery.ScrollTo](http://flesler.blogspot.com/2007/10/jqueryscrollto.html) – 2012-02-19 04:40:56

+0

我將如何使用它?作爲一個onclick函數,只需將一個id放在這裏onclck =「jQuery.ScrollTo(bottom)」 – 2012-02-19 13:42:36

回答

6

因爲沒有人真正回答這個問題之前,我會用我發現誰需要它的人回答。

所有你需要做的就是這樣的

<a href="#bottom">scroll to bottom</a> 

<p id="bottom">bottom</p> 

正常的錨鏈接,然後添加這段JavaScript代碼,如果你需要在移動改變什麼,看看JavaScript註釋

<script> 
    $(function() { 

     function filterPath(string) { 
      return string 
      .replace(/^\//,'') 
      .replace(/(index|default).[a-zA-Z]{3,4}$/,'') 
      .replace(/\/$/,''); 
     } 

     var locationPath = filterPath(location.pathname); 
     var scrollElem = scrollableElement('html', 'body'); 

     // Any links with hash tags in them (can't do ^= because of fully qualified URL potential) 
     $('a[href*=#]').each(function() { 

      // Ensure it's a same-page link 
      var thisPath = filterPath(this.pathname) || locationPath; 
      if ( locationPath == thisPath 
       && (location.hostname == this.hostname || !this.hostname) 
       && this.hash.replace(/#/,'')) { 

        // Ensure target exists 
        var $target = $(this.hash), target = this.hash; 
        if (target) { 

         // Find location of target 
         var targetOffset = $target.offset().top; 
         $(this).click(function(event) { 

          // Prevent jump-down 
          event.preventDefault(); 

          // Animate to target 
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() { 

           // Set hash in URL after animation successful 
           location.hash = target; 

          }); 
         }); 
        } 
      } 

     }); 

     // Use the first element that is "scrollable" (cross-browser fix?) 
     function scrollableElement(els) { 
      for (var i = 0, argLength = arguments.length; i <argLength; i++) { 
       var el = arguments[i], 
       $scrollElement = $(el); 
       if ($scrollElement.scrollTop()> 0) { 
        return el; 
       } else { 
        $scrollElement.scrollTop(1); 
        var isScrollable = $scrollElement.scrollTop()> 0; 
        $scrollElement.scrollTop(0); 
        if (isScrollable) { 
         return el; 
        } 
       } 
      } 
      return []; 
     } 

    }); 
    </script>