jQuery smooth scroll在第一个锚点返回错误

时间:2014-02-23 02:06:05

标签: jquery html

我想使用平滑滚动转到我主页上的主播。我使用这个jQuery代码:

$(document).ready(function(){
    $('a').click(function(){
        $('html, body').animate({
            scrollTop: $($.attr(this, 'href')).offset().top
        }, 1000);
            return false;
    });
});

这是HTML代码:

<div id="menu">
        <div id="menu-contain">
            <ul>
                <li><a class="home" href="#">Home</a></li>
                <li><a class="about" href="#about">About</a></li>
                <li><a class="projects" href="#projects">Projects</a></li>
                <li><a class="contact" href="#contact">Contact</a></li>
            </ul>
        </div>
    </div>

这适用于每个锚,但第一个。如果我看一下控制台,如果我点击第一个链接就会出错:

Cannot read property 'top' of undefined

我发现了很多线程来解决这个错误,但我找不到适用于我的解决方案。

建议赞赏:)

1 个答案:

答案 0 :(得分:1)

在使用之前检查目标元素是否存在:

$('a').click(function(){
    var $target = $($.attr(this, 'href'));

    if ( ! $target.length ) return;

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 1000);

    return false;
});

您还应该将选择器缓存在那里。 See this thread for more details