📅  最后修改于: 2023-12-03 14:43:11.629000             🧑  作者: Mango
When we have a web page with long content, it can be difficult for users to navigate to the specific sections they need to reach. The usual way of solving this problem is by using hyperlinks pointing to the specific section, but the user experience may not be optimal as it may jump abruptly between sections. To enhance the user experience, we can add a smooth scrolling effect to our hyperlinks using jQuery.
jQuery is a fast, lightweight, and feature-rich JavaScript library. It simplifies HTML document manipulation, event handling, animation, and AJAX interactions for fast web development.
Smooth scroll is a JavaScript technique that animates scrolling to anchor links. Instead of it jumping directly, the scroll will transition smoothly, giving a better user experience. It involves adding a small piece of code that overrides the default hyperlink behavior and adds smooth scrolling to the page.
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
href
attribute values starting with #
:$(document).ready(function(){
$('a[href^="#"]').on('click', function(event) {
var target = $(this.getAttribute('href'));
if( target.length ) {
event.preventDefault();
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
}
});
});
<h2 id="section-1">Section 1</h2>
<a href="#section-1">Go to Section 1</a>
jQuery smooth scroll is a simple and effective way to add smooth scrolling effects to navigation links on long web pages. It provides a better user experience by making navigation more fluid and enjoyable. With this snippet, you can quickly add this feature to your web page and impress your users.