使用jQuery的setTimeout()函数进行Anchor Scrolling

时间:2014-10-17 15:53:39

标签: javascript settimeout anchor-scroll

我还在学习如何使用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>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

在超时中包裹动画:

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

答案 1 :(得分: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);
    });
});

答案 2 :(得分:0)

setTimeout(function(){

    //insert code here

}, 1000);

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