Home Web Front-end JS Tutorial How to use Sticky component to implement tab navigation and scroll navigation with sticky effect_javascript skills

How to use Sticky component to implement tab navigation and scroll navigation with sticky effect_javascript skills

May 16, 2016 pm 03:10 PM
sticky

Sticky components are usually used in navigation bars or toolbars. When the web page scrolls in a certain area, elements such as the navigation bar or toolbar are fixed at the top or bottom of the page to facilitate users to quickly perform the functions provided by such elements. operate.

In this article Improved implementation of Sticky component provides an improved version of the sticky component and applies the demonstration effect to his blog. With a simple component like sticky, we can use it to develop richer effects, such as tab navigation and scroll navigation to be introduced in this article. The implementation is simple and the demonstration effect is as follows:

tab navigation (corresponding to tab-sticky.html):

Scroll navigation (corresponds to nav-scroll-sticky.html):

1. Implementation of tab navigation

The requirements for tab navigation are: when clicking a navigation item, in addition to switching the tab content, you must also control the scrolling, put the tab content to be displayed on top, and display it just below the sticky element. Since the demo is made with bootstrap, the tab component provided by bootstrap is very simple and easy to use. We can perform scrolling control processing in the event callback of shown.bs.tab provided by the tab component, so this effect is relatively easy to implement:

<script>
var $target = $('#target');
new Sticky('#sticky', {
unStickyDistance: 60,
target: $target,
wait: 1,
isFixedWidth: false,
getStickyWidth: function($elem) {
return $elem.parent()[0].offsetWidth;
}
});
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
window.scrollTo(0, $target[0].getBoundingClientRect().top + getPageScrollTop() + 1);
});
function getPageScrollTop() {
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
}
</script>
Copy after login

html structure:


2. Scroll navigation implementation

Scrolling navigation is relatively troublesome. In the tab component, only the tab content corresponding to the currently activated tab item will be displayed. In scrolling navigation, all the content to be navigated has been rendered on the page. Its requirements Yes:

1) When clicking a navigation item, control the scrolling of the page and automatically display the content corresponding to the clicked navigation item on top, and it should be displayed just below the sticky element;

2) When the page scrolls, the active style is automatically added to the corresponding navigation item based on the currently displayed navigation content.

Although it sounds complicated, the implementation in the demo is relatively easy:

<script>
var $sticky = $('#sticky');
var $target = $('#target');
new Sticky($sticky, {
unStickyDistance: 60,
target: $target,
wait: 1,
isFixedWidth: false,
getStickyWidth: function ($elem) {
return $elem.parent()[0].offsetWidth;
}
});
var offsetTop = 60;
//实现点击tab项自动滚动到导航内容的效果
$sticky.on('click', 'a', function (e) {
e.preventDefault();
var $this = $(e.currentTarget);
var $parent = $this.parent();
if($parent.hasClass('active')) return;
$sticky.find('li.active').removeClass('active');
$parent.addClass('active');
var target = $this.data('target') || $this.attr('href');
var $target = $(target);
window.scrollTo(0, Math.floor($target[0].getBoundingClientRect().top) + getPageScrollTop() - offsetTop);
});
/**
* Math.floor是解决rect.top或rect.bottom带小数问题
*/
//实现滚动时根据当前显示的导航内容自动给相应的导航项添加active样式
$(window).scroll(throttle(function(){
var $curItem = $sticky.find('a').filter('[href=' + getCurTarget() + ']');
var $parent = $curItem.parent();
if($parent.hasClass('active')) return;
//最后的blur是为了去掉:active及:focus伪类的样式
$sticky.find('li.active').removeClass('active').find('a').trigger('blur');
$parent.addClass('active');
},1));
//获取当前显示的导航内容元素的id
function getCurTarget() {
for(var targets = ['#First', '#Second', '#Third'], i = 0, l = targets.length; i < l; i++) {
var curRect = $(targets[i])[0].getBoundingClientRect();
if(Math.floor(curRect.top) <= offsetTop && Math.floor(curRect.bottom) > offsetTop) {
return targets[i];
}
}
return targets[0];
}
function getPageScrollTop() {
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
}
//这个函数在实际工作中是应该抽出来的,否则sticky.js里面还有一份重复的
function throttle(func, wait) {
var timer = null;
return function () {
var self = this, args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(function () {
return typeof func === 'function' && func.apply(self, args);
}, wait);
}
}
</script>
Copy after login

html structure:


3. Summary

This article combines the sticky component to provide two navigation effect implementations, which are compatible with IE9+, firefox and chrome. If you are interested, you can download the source code and learn more about it. When implementing tab navigation, it is very easy to implement because of the bs tab component. There is no need to encapsulate the sticky and tab components to form a new component. After all, the implementation code of the effect is relatively simple. When implementing scrolling navigation, because the tab component is not used, the two demand points of scrolling navigation are implemented separately. In actual situations, these two functions can be encapsulated into two independent components or one component. In this way, the implementation code can be written as simple as tab navigation. However, this article does not introduce the writing method of these two components in depth, because this is not the main content of this article. Although I really want to do this, I will definitely write more in the future. This blog will introduce these two components. It is simply a waste of opportunity to not build a wheel for a simple thing. When achieving these two effects, there are also two gains:

1) Firefox and IE, let the web page first and then refresh it. Although the web page will still be displayed at the refreshed position, the scroll event will not be triggered. Therefore, if you make scroll-related components in the future, you must take the initiative when the component is initialized. A scroll-related callback;

2) The value related to the rect object returned by getBoundingClientRect may be a decimal number under IE and Firefox, such as 60.2222299999. Such a number may not be consistent with the expected situation when making judgments, leading to some unexpected BUGs. If you are not particularly strict, you can use Math.floor to round these values ​​and then use them for calculation or judgment. For example, in the scroll navigation implementation, the value of rect.top is 60.2222299999, and the value of offsetTop is 60. It is expected that the condition curRect.top <= offsetTop can be established, but it is not established because of the decimal.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles