錨點跳轉過渡動畫


錨點跳轉過渡動畫

jQuery實現

此技術非常簡單。

  1. 像往常一樣設置鏈接, 例如: href =“#comments”(comments是目標的ID)

  2. 在link元素上添加一個class =“ scroll”屬性,現在看起來像這樣:

    <a href="#comments" class="scroll">
      滾動到評論
    </a>
  3. 最后,在合適的位置添加以下jQuery代碼:

    jQuery(document).ready(function($) {
    $(".scroll").click(function(event){
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
    });
    });

為了方便,$('.scroll') 選擇器可以使用 $('a[href*=#]'),並且多個元素間可以用逗號隔開 $('a[href*=#]','a[href*=#]')。

這就是全部🙂

實施此腳本的一個常見錯誤是為目標使用“命名錨”,而不是目標元素上的id屬性。如果由於某種原因(例如,由於所見即所得的限制)而被命名錨定卡住,則可以嘗試從Giles進行以下修改:

$('html,body').animate({scrollTop:$('[name="'+this.hash.substring(1)+'"]').offset().top}, 500);

參考鏈接:http://www.sycha.com/jquery-smooth-scrolling-internal-anchor-links

 

scroll-behavior屬性(不建議)

如果您不介意不支持所有主流瀏覽器(僅Firefox 36 +,Chrome 61+和Opera 48+),請使用錨點鏈接和此單個屬性作為滾動容器:

scroll-behavior: smooth;

像這樣使用它:

<head>
<style type="text/css">
   html {
     scroll-behavior: smooth;
  }
</style>
</head>
<body id="body">
<a href="#foo">Go to foo!</a>

<!-- Some content -->

<div id="foo">That's foo.</div>
<a href="#body">Back to top</a>
</body>

示例:垂直滾動斜向滾動演示Demo(但它不支持移動端)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM