Smooth Scrolling when Clicking an Anchor Link
When navigating a webpage with anchor links, users expect a seamless transition to the target section. However, default scrolling behavior can be abrupt. This article explores techniques to achieve smooth scrolling when clicking anchor links.
Native Support
Browsers like Chrome and Firefox have introduced native support for smooth scrolling. This is implemented using the "behavior" property with the value "smooth" when scrolling into view:
document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); document.querySelector(this.getAttribute('href')).scrollIntoView({ behavior: 'smooth' }); }); });
jQuery Plugin
For older browsers, a jQuery plugin can smooth the scrolling animation. This technique uses the "animate" method to move the page to the target section:
$(document).on('click', 'a[href^="#"]', function (event) { event.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500); });
Enhanced Technique
If the target element lacks an ID, the following modified jQuery plugin can be used:
$('a[href^="#"]').click(function () { $('html, body').animate({ scrollTop: $('[name="' $.attr(this, 'href').substr(1) '"]').offset().top }, 500); return false; });
Performance Optimization
Caching the "$('html, body')" selector within a variable enhances performance:
var $root = $('html, body'); $('a[href^="#"]').click(function () { $root.animate({ scrollTop: $( $.attr(this, 'href') ).offset().top }, 500); return false; });
Preserving URL Hash
To update the URL hash upon smooth scrolling, use the "animate" callback:
var $root = $('html, body'); $('a[href^="#"]').click(function() { var href = $.attr(this, 'href'); $root.animate({ scrollTop: $(href).offset().top }, 500, function () { window.location.hash = href; }); return false; });
By implementing one of these techniques, you can provide a polished and user-friendly scrolling experience when navigating your page using anchor links.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3