Freitag, 27. Oktober 2023 - Lesezeit: ~1 Minute
Ein Parallax Scroll Effekt (zu sehen auf dieser Seite) ist mit wenigen Schritten auf einer Seite eingebaut.
Man baut ein div auf der Seite ein:
<div id="background">
und versieht es mit folgender CSS Regel:
#background {
position: fixed;
top: 0;
left: 0;
width: 100%;
/* Höhe 110 Prozent wegen Parallax Scrolling */
height: 110%;
background-image: url("../img/bg.jpg");
background-size: auto, auto, 100% auto;
background-position: top, center, top center;
background-repeat: no-repeat;
background-attachment: scroll, scroll, scroll;
z-index: -1
}
Mit folgendem Stückchen JavaScript scrollt der Hintergrund dann weich bis zum Seitenende mit:
$(function () {
var $el = $('#background');
$(window).on('scroll', function () {
//Aktuelle Scrollposition
var scroll = $(document).scrollTop();
//Totale scrollposition
var total = $(document).height() - $(window).height();
//Prozentualer Wert
var percent = scroll / total;
$el.css({
// Wir bewegen den Hintergrund insgesamt um 10 %
'top': (percent * -10) + '%'
});
});
});