अरे! इससे पहले कि आप जावास्क्रिप्ट-आधारित चिकनी स्क्रॉलिंग के खरगोश के छेद से बहुत नीचे जाएं, पता करें कि इसके लिए एक देशी सीएसएस सुविधा है scroll-behavior
:।
html ( scroll-behavior: smooth; )
और इससे पहले कि आप मदद के लिए jQuery जैसी लाइब्रेरी के लिए पहुँचें, इस तरह से चिकनी स्क्रॉलिंग का एक देशी जावास्क्रिप्ट संस्करण भी है:
// Scroll to specific values // scrollTo is the same window.scroll(( top: 2500, left: 0, behavior: 'smooth' )); // Scroll certain amounts from current position window.scrollBy(( top: 100, // could be negative value left: 0, behavior: 'smooth' )); // Scroll to a certain element document.querySelector('.hello').scrollIntoView(( behavior: 'smooth' ));
डस्टन कस्तेन के पास इसके लिए एक पॉलीफिल है। और आप शायद इसके लिए केवल तभी पहुंचेंगे जब आप उस पृष्ठ को स्क्रॉल करने के साथ कुछ कर रहे थे जो #target जंप लिंक और CSS के साथ नहीं किया जा सकता था।
चिकना स्क्रॉलिंग की पहुंच
चिकनी स्क्रॉलिंग के लिए आप जो भी तकनीक का उपयोग करते हैं, पहुंच एक चिंता का विषय है। उदाहरण के लिए, यदि आप किसी #hash
लिंक पर क्लिक करते हैं , तो मूल व्यवहार ब्राउज़र के लिए उस आईडी से मेल खाने वाले तत्व पर ध्यान केंद्रित करने के लिए होता है। पेज स्क्रॉल हो सकता है, लेकिन स्क्रॉलिंग फोकस बदलने का एक साइड इफेक्ट है।
यदि आप डिफ़ॉल्ट फ़ोकस-चेंजिंग व्यवहार (जो आपको करना है, तुरंत स्क्रॉलिंग को रोकने और चिकनी स्क्रॉलिंग को सक्षम करने के लिए) को ओवरराइड करते हैं , तो आपको फ़ोकस-चेंजिंग को स्वयं हैंडल करना होगा ।
हीथर मिगलोरिसी ने इस बारे में लिखा, कोड सॉल्यूशंस के साथ, स्मूथ स्क्रॉलिंग एंड एक्सेसिबिलिटी में।
JQuery के साथ चिकनी स्क्रॉल
jQuery भी ऐसा कर सकता है। यहाँ एक ही पृष्ठ पर एक लंगर के लिए एक चिकनी पृष्ठ स्क्रॉल करने के लिए कोड है। इसमें कुछ तर्क दिए गए हैं जो उन जंप लिंक की पहचान करते हैं, और अन्य लिंक को लक्षित नहीं करते हैं।
// Select all links with hashes $('a(href*="#")') // Remove links that don't actually link to anything .not('(href="#")') .not('(href="#0")') .click(function(event) ( // On-page links if ( location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname ) ( // Figure out element to scroll to var target = $(this.hash); target = target.length ? target : $('(name=' + this.hash.slice(1) + ')'); // Does a scroll target exist? if (target.length) ( // Only prevent default if animation is actually gonna happen event.preventDefault(); $('html, body').animate(( scrollTop: target.offset().top ), 1000, function() ( // Callback after animation // Must change focus! var $target = $(target); $target.focus(); if ($target.is(":focus")) ( // Checking if the target was focused return false; ) else ( $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable $target.focus(); // Set focus again ); )); ) ) ));
CodePen पर Chris Coyier (@chriscoyier) द्वारा jQuery में पेन स्मूथ पेज स्क्रॉलिंग देखें।
यदि आपने इस कोड का उपयोग किया है और आप सभी के साथ इस तरह से काम कर रहे हैं, तो?, ऊपर पहुंच के बारे में सामग्री पढ़ें।