How to Use the Sticky component to implement tab navigation and scroll navigation with sticky effect _ javascript skills

Source: Internet
Author: User
The sticky component is usually used in a navigation bar or toolbar. When a webpage is rolling in a certain area, the elements such as the navigation bar or toolbar are fixed at the top or bottom of the page, it is convenient for users to quickly operate the sticky component provided by such elements. It is usually used in navigation bar or toolbar. When a webpage is rolling in a certain area, you can pin the navigation bar or toolbar to the top or bottom of the page for quick operations.

In this article, the improved implementation of the Sticky component provides an improved version of the sticky component, and applies the demonstration effect to your blog. With a simple component like sticky, we can use it to develop richer effects, such as the tab navigation and scroll navigation described in this article. Simple implementation:

Tabnavigation (tab-sticky.html ):

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

1. Implementation of tab navigation

The requirement for tab navigation is: When you click a navigation item, in addition to switching the tab content, you also need to control the scrolling. The tab content to be displayed must be placed on top, and be displayed just below the sticky element. Because the demo uses bootstrap, the tab component provided by bootstrap is very simple and easy to use. We can use shown provided by the tab component. bs. the tab Event Callback is used for rolling control, so this effect is easier 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. Implement rolling navigation

Scroll navigation is a little more troublesome. In the tab component, only the tab content corresponding to the currently activated tab items is displayed, while in the scroll navigation, all the content to be navigated has been rendered in the page, and its requirements are as follows:

1) When you click a navigation item, control the page to scroll. The content corresponding to the clicked navigation item is automatically displayed on the top of the page and must be displayed under the sticky element;

2) When the page is scrolling, an 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; // click the tab to automatically scroll to the navigation content. $ 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 is the solution for rect. top or rect. bottom with decimals * // automatically adds an active style to the corresponding navigation item based on the currently displayed navigation content when scrolling. $ (window ). scroll (throttle (function () {var $ curItem = $ sticky. find ('A '). filter ('[href =' + getCurTarget () + ']'); var $ parent = $ curItem. parent (); if ($ parent. hasClass ('active') return; // The final blur is used to remove: active and: focus pseudo class styles $ sticky. find ('Li. active '). removeClass ('active '). find ('A '). trigger ('blur'); $ parent. addClass ('active') ;}, 1); // gets the idfunction 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.doc umentElement. scrollTop | document. body. scrollTop;} // this function should be extracted in actual work; otherwise sticky. in js, there is a duplicate 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, combined with the sticky component, provides two types of navigation effects, compatible with IE9 +, firefox and chrome. If you are interested, you can download the source code and learn more. When implementing tab navigation, it is very easy to implement the bs tab component, and there is no need to encapsulate sticky and tab components to form a new component, after all, the implementation code of the effect is relatively simple. When implementing the rolling navigation, because the tab component is not used, the two requirements of the rolling navigation are implemented independently. In actual situations, these two functions can be encapsulated into two independent components or one component, so that code writing can be as simple as tab navigation, however, this article has not gone into detail about the writing of these two components, because this is not the main content of this article. Although I would like to do so, I will certainly write a blog to introduce these two components in the future, simple things are a waste of opportunities without building a wheel. When achieving these two effects, there are also two gains:

1) firefox and IE: Let the web page be refreshed first, and then refresh. Although the web page will be displayed in the refresh location, the scroll event will not be triggered, so we will make scroll-related components in the future, you must take the initiative to initiate a scroll-related callback during component initialization;

2) The values related to the rect object returned by getBoundingClientRect may be decimal places in IE and firefox, such as 60.2222299999. Such numbers may not match the expectations during the judgment, some unexpected bugs may occur. If not, you can use Math. floor performs an integer on these values, which are then used for calculation or judgment. For example, in rolling navigation implementation, rect. the top value is 60.2222299999, The offsetTop value is 60, and the expected value is curRect. the top <= offsetTop condition can be true because of decimal places.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.