使用jQuery's setTimout()函数用于锚点滚动

Using jQuery's setTimout() Function For Anchor Scrolling

本文关键字:函数 用于 滚动 setTimout jQuery 使用      更新时间:2023-09-26

我仍在学习如何使用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>

在超时时包装动画:

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

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

$(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);
    });
});
setTimeout(function(){
    //insert code here
}, 1000);

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