1

代码:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

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

单击时,脚本应该会慢慢移动页面上的位置。由于某种原因,它根本不起作用。我是 JS 的新手,所以不确定我错过了什么。有任何想法吗?

4

2 回答 2

2

你有语法错误

$(document).ready(function() {//<<< here where having an extra `)`
    $('a').click(function(){
    var a = $(this).offset().top;// please replace `this` with the selector of the element you want to scroll to
    $('html, body').animate({'scrollTop' : a}// set the correct offset
    , 100000);
    return false;
})
});
于 2013-08-25T16:38:28.860 回答
2

除了)函数括号后面的多余内容(顺便说一句,它不恰当地关闭了ready方法)会导致语法错误,语句下方的括号后面还有一个省略的半色return false(是的,分号是可选的,但最好不要依赖 JavaScript 的自动功能来猜测行结束的位置)。顺便说一句,我建议稍微改变一下:

//                           V- removed the extra ')'
$(document).ready(function () {
    $('a').click(function () {
        /* caching the element you want to scroll
           to (using 'getAttribute()', rather than invoking jQuery,
           to retrieve the 'href' attribute, though still wrapping into
           a jQuery object to make use of the methods */
        var target = $(this.getAttribute('href'));
        $('html, body').animate({
            'scrollTop': target.offset().top
        }, 10000);
        return false;
    }); // <-- added the semi-colon
});

JS 小提琴演示

于 2013-08-25T16:48:12.340 回答