HTML, CSS and jQuery: Build a Beautiful Vertical Scroll Navigation
In web design, the navigation bar is a very important component. A beautiful, easy-to-use navigation bar provides a good user experience and provides users with an intuitive navigation system. In this article, we'll build a beautiful vertical scrolling navigation bar using HTML, CSS, and jQuery, and provide concrete code examples.
First, we need to determine the HTML structure of the navigation bar. In this example, we will use an unordered list
to create the navigation menu, and list items< with the style class
.nav-item;li>
to represent each navigation button. Each navigation button contains aelement that displays the text content of the navigation button.
Next, we use CSS styles to design and layout the navigation bar. Here is a basic styling example:
.nav-menu { list-style: none; margin: 0; padding: 0; } .nav-item { display: block; margin-bottom: 10px; } .nav-item a { display: block; padding: 10px; text-decoration: none; color: #333; background-color: #f1f1f1; border-radius: 3px; } .nav-item.active a { color: #fff; background-color: #333; }
With these basic styles, we can create a simple vertical navigation bar and apply different styles to the active navigation buttons.
Now, we need to add a smooth scrolling effect to the navigation bar, so that when the navigation button is clicked, the page will scroll smoothly to the corresponding section. To achieve this effect we will use the jQuery library.
First, add the following code before thetag at the bottom of the HTML file to introduce the jQuery library:
Then, add the following code in the JavaScript file:
$(document).ready(function() { // 点击导航按钮时,平滑滚动到相应的节段 $('a[href^="#"]').on('click', function(event) { event.preventDefault(); var target = $(this.getAttribute('href')); if (target.length) { $('html, body').stop().animate({ scrollTop: target.offset().top }, 1000); } }); // 根据滚动位置添加活动导航按钮样式 $(window).scroll(function() { var scrollDistance = $(window).scrollTop(); $('.nav-item').each(function(i) { if ($(this).position().top <= scrollDistance + 100) { $('.nav-item.active').removeClass('active'); $('.nav-item').eq(i).addClass('active'); } }); }).scroll(); });
The above code implements two functions:
animate()
function to achieve a smooth scrolling effect.scroll()
function to listen to page scroll events and add active styles to the current section based on the scroll position.By adding the above jQuery code to the web page, we have completed a beautiful vertical scrolling navigation bar.
To sum up, by combining HTML, CSS and jQuery, we can easily and elegantly build a beautiful vertical scrolling navigation bar. Through this example, we can better understand how to apply these techniques to improve the user experience of web design.
The above is the detailed content of HTML, CSS, and jQuery: Build a beautiful vertical scroll navigation. For more information, please follow other related articles on the PHP Chinese website!