jQuery平滑滚动问题

时间:2014-12-24 05:46:53

标签: javascript jquery ios html5 scroll

我已经按照本教程学习了如何编写一些jQuery来在我的网站上获得一个漂亮的平滑滚动。这是你参考{t 3}}

的啧啧

然而,在我的jQ代码中似乎存在一个问题并且动画无法正常工作......如果有一套新的眼睛就可以看到我出错的地方以及如何修复它会很不错。

到目前为止,控制台告诉我,我有这个问题TypeError: Cannot read property 'top' of undefined

这是我目前的版本 https://www.youtube.com/watch?v=S6pzabpUmoc

这是我的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();
    }        

});

2 个答案:

答案 0 :(得分:1)

下面&#39;哈希&#39;肯定是你有一个erorr,Uncaught TypeError:无法读取属性&#39; left&#39;由于未定义的元素属性访问而发生未定义。

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

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

答案 1 :(得分:0)

因为$("a[name="+hash+"]")没有返回任何内容。也许你应该检查它是否在动画开始前返回一些东西。就像这样:

if($toElement.length){

    // do something

}
相关问题