Использование функции setTimout() в jQuery для прокрутки привязки
Я все еще учусь использовать 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>
3 ответа
Решение
Заверните анимацию в тайм-аут:
setTimeout(function() {
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 2
}, 900, 'easeInOutExpo', function () {
window.location.hash = target;
});
}, 1000);
setTimeout(function(){
//insert code here
}, 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);
});
});