Как настроить плавную прокрутку для остановки в определенной позиции сверху с помощью jQuery?

Опубликовано: 30 Ноября, 2021

Метод scrollTop () в jQuery используется для прокрутки к определенной части страницы. Анимация этого метода с помощью доступных встроенных анимаций может сделать прокрутку более плавной. И вычитание из него указанного значения остановит прокрутку сверху.

Подход: хэш-часть ссылки привязки сначала извлекается с помощью свойства hash, а ее положение на странице определяется с помощью метода offset (). Затем для этого хеш-значения вызывается метод scrollTop () для прокрутки до этого места. Этот метод анимируется путем включения его в метод animate () и указания продолжительности используемой анимации в миллисекундах. При большем значении анимация будет выполняться медленнее, чем при меньшем значении. Это плавно анимирует все привязанные ссылки на странице при нажатии на них. И затем мы вычтем указанное значение, чтобы остановить плавную прокрутку до остановки сверху.

Пример:

HTML

<!DOCTYPE html>
< html >
< head >
< title >
How to set smooth scrolling to stop at
a specific position from the top using
jQuery?
</ title >
<!-- JQuery Script -->
< script src =
</ script >
<!-- Style to make scrollbar appear -->
< style >
.scroll {
height: 1000px;
background-color: teal;
color: white;
}
</ style >
</ head >
< body >
< h1 style = "color: green" >
GeeksforGeeks
</ h1 >
< b >
How to set smooth scrolling to stop at
a specific position from the top using
jQuery?
</ b >
< p id = "dest" >
Click on the button below to
scroll to the top of the page.
</ p >
< p class = "scroll" >
GeeksforGeeks is a computer science
portal. This is a large scrollable
area.
</ p >
< a href = "#dest" >
Scroll to top
</ a >
<!-- jQuery for smooth scrolling to a
specific position from top -->
< script >
// Define selector for selecting
// anchor links with the hash
let anchorSelector = 'a[href^="#"]';
$(anchorSelector).on('click', function (e) {
// Prevent scrolling if the
// hash value is blank
e.preventDefault();
// Get the destination to scroll to
// using the hash property
let destination = $(this.hash);
// Get the postion of the destination
// using the coordinates returned by
// offset() method and subtracting 50px
// from it.
let scrollPosition
= destination.offset().top - 50;
// Specify animation duration
let animationDuration = 500;
// Animate the html/body with
// the scrollTop() method
$('html, body').animate({
scrollTop: scrollPosition
}, animationDuration);
});
</ script >
</ body >
</ html >

Выход: