JavaScript - Smooth Scrolling

Aus Wikizone
Version vom 22. Juli 2021, 07:22 Uhr von 134.3.85.26 (Diskussion)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu: Navigation, Suche

Es wäre so einfach mit CSS wenn es alle unterstützen würden. Edge, IE und Safari tun es stand 2020 nicht :-(

Die unkomplizierteste Lösung für mich 2020 ist immer noch ein jQuery Snippet

$( document ).ready(function() {
	//sscroll
	//$(document).on('click', '.nav a[href^="#"]', function (event) {
    shift = 58
    duration = 250
    scrollElement = 'a.scroll'
	$(document).on('click', scrollElement, function (event) {
		event.preventDefault();
		$('html, body').animate({
			scrollTop: $($.attr(this, 'href')).offset().top - shift
		}, duration);
	});
});

Viele andere Löungen inklusive. Polyfills, haben in Safari nicht funktioniert. Eine Vanilla Lösung Daher mit JavaScript (siehe auch Snippets für jQuery Lösungen).

https://perishablepress.com/vanilla-javascript-scroll-anchor/


More smooth scroll techniques

Smooth Scroll (Vanilla JS)
Smooth Scrolling (jQuery)
Skinny.js (jQuery)

cferdinandi smooth-scroll[Bearbeiten]

Eines der verbreitetsten und recht schmal ist dieses Vanilla JS

https://github.com/cferdinandi/smooth-scroll

Only CSS Solution[Bearbeiten]

Funktioniert 2021 überall außer IE und Safari (dort nur im experimental mode).

Beispiel

.module {
  scroll-behavior: [ auto | smooth ];
}

More infos at CSS-Tricks and caniuse. Thanks to DKeu for the tip!