簡體   English   中英

jQuery外部鏈接錨點動畫

[英]jQuery external link anchor animate

找不到正確答案。 我想打開頁面,然后以動畫方式滾動到我叫的ID

這是我的代碼。

jQuery查詢

   $(window).bind("load", function () {
              var urlHash = window.location.href.split("#")[1];
                $('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 1000);
    }); 

HTML

<div class="space"></div>
<div id="anchor">This is anchor</div>

的CSS

.space{height:800px;}
#anchor{font-size:25px;height:800px;}

jQuery無法正常工作,因此我將以下代碼粘貼到控制台

 $('html,body').animate({ scrollTop: $('a[href="#' + anchor+ '"]').offset().top}, 1000);

錯誤說

TypeError:無法讀取未定義的屬性“ top”

http://jsfiddle.net/4mjmw/1/

我該如何解決這個錯誤? 謝謝

此代碼有效: http : //jsfiddle.net/4mjmw/4/

演示: http : //jsfiddle.net/4mjmw/4/show/#abc

我向錨添加了href,並將腳本移至HTML。

$(window).bind("load", function () {
          var urlHash = window.location.href.split("#")[1];
            $('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 1000);
      });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM