2014-12-24 74 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 

}