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

WBOY
WBOYOriginal
2016-05-16 15:10:081846browse

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>

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>

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:
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