2014-12-24 73 views
0

我已經按照本教程介紹瞭如何編寫一點jQuery以在我的網站上獲得很好的平滑滾動。這裏是你參考的嘖嘖https://www.youtube.com/watch?v=S6pzabpUmocjQuery平滑滾動問題

但是在我的jQ代碼的某個地方似乎存在問題,並且動畫無法正常工作......如果有一組新的目光觀看它會很好我錯了,如何解決它。

隨着這一刻的控制檯告訴我,我有這個問題TypeError: Cannot read property 'top' of undefined

這是我當前構建 http://kapena.github.io/pp_web/#services-pp

這裏是我的JQ代碼

$(function() { 
    // catch all clicks on page 
    $('a').click(function() { 

    // check if has hash 
    if(this.hash) { 

    // get rid of the # sign 
    var hash = this.hash.substr(1); 

    //get the position of the <a name> 
    var $toElement = $("a[name="+hash+"]"); 
    var toPosition = $toElement.position().top; 

    // scroll/animate that element 
    $ ('body,html').animate({ 
     scrollTop : toPosition 
    },2000,"easeOutExpo"); 

    // don't do the jump 
    return false; 

    } 

    }); 

    if(location.hash) { 
     var hash = location.hash 
     window.scroll(0,0); 
     $('a[href='+hash+"]").click(); 
    }   

}); 

+0

你可以控制檯登錄var hash,並在這裏添加 –

+0

你可以添加HTML嗎? –

回答

1
'hash'下面的

是你肯定有一個erorr的地方,Uncaught TypeError:Can not由於未定義的元素屬性accesssing發生未定義的屬性'left'。

$toElement = = $("a[name="+hash+"]"); // this hash is undifined or wrong value 

// this lead following line to throw the error 
var toPosition = $toElement.position().top; 
+0

所以你說的波紋管散列是我有我的錯誤'/ /這導致下面的行拋出錯誤 var toPosition = $ toElement.position()。top;'你在這裏發佈的代碼應該修復問題??我真的是jQ的新手.. – roygbiv

+0

哈希值設置不正確check console.log(hash);並看到哈希值必須是一些錯誤的值 –

0

因爲$("a[name="+hash+"]")什麼也沒有返回。也許你應該檢查它是否在動畫開始之前返回一些東西。就像這樣:

if($toElement.length){ 

    // do something 

}