0

我仍在学习如何使用 jQuery,并且我有这个脚本可以平滑滚动到我页面上的锚点。我希望它在开始滚动之前等待一秒钟,因为我有一个需要关闭的菜单。我假设我需要使用该setTimeout()功能,但无法弄清楚如何在下面的代码中正确实现它。

<script>

  $(document).ready(function(){
	$('a[href^="#"]').on('click',function (e) {
	    e.preventDefault();

	    var target = this.hash,
	    $target = $(target);

	    $('html, body').stop().animate({
	        'scrollTop': $target.offset().top - 2
	    }, 900, 'easeInOutExpo', function () {
	        window.location.hash = target;
	    });
	});
});

</script>

4

3 回答 3

0

在超时中包装动画:

setTimeout(function() {
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top - 2
    }, 900, 'easeInOutExpo', function () {
        window.location.hash = target;
    });
}, 1000);
于 2014-10-17T15:54:57.987 回答
0

您需要在点击后在事件中添加它。像这样:

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();
        // a settimeout is a function with two parameters: a function to execute, 
        // and a time to delay. So whatever you want to do, you can wrap in what is
        // called an 'anonymous' function. Used once, then forgotten about.
        setTimeout(function(){
            var target = this.hash,
            $target = $(target);

            $('html, body').stop().animate({
                'scrollTop': $target.offset().top - 2
            }, 900, 'easeInOutExpo', function () {
                window.location.hash = target;
            });
        }, 1000);
    });
});
于 2014-10-17T15:55:16.957 回答
0
setTimeout(function(){

    //insert code here

}, 1000);

http://www.w3schools.com/jsref/met_win_settimeout.asp

于 2014-10-17T15:55:38.707 回答