Verwenden von scrollIntoView mit einer Kopfzeile mit fester Position

Lesezeit: 12 Minuten

Benutzer-Avatar
Corne Beukes

Ich habe eine Website mit einem Header auf position: fixed. Auf einer meiner Seiten verwende ich scrollIntoView(true) auf einem Element. Mein Problem ist, wann scrollIntoView aufgerufen wird, wird das Element unterhalb der Kopfzeile positioniert. Wie würde ich das beheben, damit das Element direkt unter der Kopfzeile angezeigt wird?

Ich verwende das Bootstrap-Framework und der Header ist mit gestylt navbar navbar-fixed-top.

  • Gute Frage. Vielen Dank

    – Titus Sutio Fanpula

    7. Oktober 2021 um 9:28 Uhr

Benutzer-Avatar
Erwähnen Sie nicht die Sicherung

Es ist ein bisschen hacky, aber hier ist ein Workaround.

var node="select your element";
var yourHeight="height of your fixed header";

// scroll to your element
node.scrollIntoView(true);

// now account for fixed header
var scrolledY = window.scrollY;

if(scrolledY){
  window.scroll(0, scrolledY - yourHeight);
}

Bearbeiten:

Ein moderner Workaround ist die Verwendung von CSS scroll-margin-top Eigenschaft in Kombination mit der :target Wähler. Ausführlich beschrieben: https://www.bram.us/2020/03/01/prevent-content-from-being-hidden-underneath-a-fixed-header-by-using-scroll-margin-top/

  • Ich habe tagelang nach dieser Antwort gesucht. Endlich gefunden. Kühl.

    – Faisal Mq

    16. Juli 2015 um 11:15 Uhr

  • Sie können auch eine imaginäre „yourHeight“ wie 1000 festlegen, wenn Ihr Header eine dynamische Größe hat.

    – Pietro Coelho

    12. April 2018 um 1:00 Uhr

  • Sie könnten Ihren Code dadurch vereinfachen window.scroll(0, node.offsetTop - yourHeight); und nicht verwenden scrollIntoView

    – jhujhul

    12. Februar 2019 um 15:29 Uhr


  • Es funktioniert, aber es respektiert nicht das native Smooth-Scrolling-Verhalten des Browsers, falls vorhanden.

    – msun

    25. März 2020 um 3:31 Uhr


  • eine Problemumgehung, die ich am nützlichsten finde (anstatt nach oben zu scrollen, scrollen Sie in die Mitte): node.scrollIntoViewIfNeeded({block: 'center'})

    – Sanyam Jain

    29. April 2020 um 7:21 Uhr

Benutzer-Avatar
Karl Horki

Bearbeiten: Obwohl weniger kompatibel (keine IE-Kompatibilität), scroll-margin-top wird dies auch lösen, wie in Arye Eidelmans Antwort erwähnt.

Sie können dies mit CSS lösen, indem Sie a anwenden padding-top und ein Negativ margin-top zu den Elementen, zu denen Sie blättern möchten.

Demo

// For demo only, no JS needed for the solution
document.querySelector('.scroll-to-working-inline').addEventListener('click', function() {
  document.querySelector('.working-inline').scrollIntoView();
});

document.querySelector('.scroll-to-working-block').addEventListener('click', function() {
  document.querySelector('.working-block').scrollIntoView();
});

document.querySelector('.scroll-to-broken').addEventListener('click', function() {
  document.querySelector('.broken').scrollIntoView();
});
/* Relevant styles */
.working-inline {
  padding-top: 60px;
  margin-top: -60px;
}

.working-block {
  padding-top: 60px;
  margin-top: -60px;
}

/* Allow scrolling to the top */
body {
  padding-top: 60px;
}

/* Only for the demo */
body { margin: 0; }

header {
  position: fixed;
  top: 0;
  background-color: tomato;
  color: white;
  width: 100%;
  height: 60px;
  line-height: 60px;
  text-align: center;
}

[class^='working'],
[class^='broken'] {
  font-size: 3rem;
}
<header>
  scroll to...
  <button class="scroll-to-working-inline">working inline element</button>
  <button class="scroll-to-working-block">working block element</button>
  <button class="scroll-to-broken">broken element</button>
</header>

<main>
  <p>Sql daemon epoch all your base are belong to us packet system perl semaphore. Interpreter warez pragma kilo worm back door baz continue chown blob unix Dennis Ritchie stack mutex bar throw fopen man pages linux. Sql suitably small values bit infinite loop pwned rm -rf.</p>
  
  <a class="working-inline">Working inline</a>
  
  <p>Syn baz man pages unix vi crack leapfrog semaphore fail pwned afk null socket cd long leet emacs Donald Knuth bin grep todo pragma stdio.h January 1, 1970. Alloc gc system new finally sql stack trace syn mainframe cat machine code memory leak server salt flood tunnel in back door thread. Bytes fatal throw ctl-c Dennis Ritchie over clock eof tera perl regex.</p>
  
  <div class="working-block">Working block element</div>
  
  <p>Public injection class unix malloc error script kiddies packet less fail int I'm sorry Dave, I'm afraid I can't do that. Tarball memory leak double rsa pwned public all your base are belong to us. False bytes bang bar tarball semaphore warez cd port daemon exception mountain dew sql mainframe gcc ifdef chown private.</p>
  
  <div class="broken">Broken element</div>
  
  <p>Daemon bubble sort protected mutex overflow grep snarf crack warez I'm compiling bit if memory leak Starcraft nak script kiddies long it's a feature. Hello world public server James T. Kirk injection terminal wannabee race condition syn alloc. Gobble leapfrog finally bypass concurrently while irc gurfle do back door blob man pages sql over clock.</p>
  
  <p>Char hello world then man pages ascii long salt while char fatal do boolean tunnel in system else foo packet sniffer float terminal int default. Trojan horse ssh ifdef /dev/null chown cache error protocol afk todo rm -rf mainframe piggyback pwned regex xss warez Starcraft try catch stdio.h bubble sort. It's a feature I'm sorry Dave, I'm afraid I can't do that *.* port bypass ip.</p>
  
  <p>Stdio.h epoch mutex flood wannabee do race condition sql access exception. Bar pragma man pages dereference flush todo highjack while buffer bit nak big-endian syn xss salt for d00dz. Leslie Lamport linux server error hexadecimal snarf tunnel in rm -rf firewall then shell all your base are belong to us.</p>

  <p>Ascii gcc grep int flood kilo linux access mailbomb hash *.* fork semaphore frack else win bar ssh Leslie Lamport. Man pages strlen cache gnu segfault tarball race condition perl packet sniffer root cookie private chown d00dz January 1, 1970. Rsa public crack bit warez throw for void concurrently ip mutex.</p>
  
  <p>Char hello world then man pages ascii long salt while char fatal do boolean tunnel in system else foo packet sniffer float terminal int default. Trojan horse ssh ifdef /dev/null chown cache error protocol afk todo rm -rf mainframe piggyback pwned regex xss warez Starcraft try catch stdio.h bubble sort. It's a feature I'm sorry Dave, I'm afraid I can't do that *.* port bypass ip.</p>
  
  <p>Stdio.h epoch mutex flood wannabee do race condition sql access exception. Bar pragma man pages dereference flush todo highjack while buffer bit nak big-endian syn xss salt for d00dz. Leslie Lamport linux server error hexadecimal snarf tunnel in rm -rf firewall then shell all your base are belong to us.</p>

  <p>Ascii gcc grep int flood kilo linux access mailbomb hash *.* fork semaphore frack else win bar ssh Leslie Lamport. Man pages strlen cache gnu segfault tarball race condition perl packet sniffer root cookie private chown d00dz January 1, 1970. Rsa public crack bit warez throw for void concurrently ip mutex.</p>
  
  <p>Char hello world then man pages ascii long salt while char fatal do boolean tunnel in system else foo packet sniffer float terminal int default. Trojan horse ssh ifdef /dev/null chown cache error protocol afk todo rm -rf mainframe piggyback pwned regex xss warez Starcraft try catch stdio.h bubble sort. It's a feature I'm sorry Dave, I'm afraid I can't do that *.* port bypass ip.</p>
  
  <p>Stdio.h epoch mutex flood wannabee do race condition sql access exception. Bar pragma man pages dereference flush todo highjack while buffer bit nak big-endian syn xss salt for d00dz. Leslie Lamport linux server error hexadecimal snarf tunnel in rm -rf firewall then shell all your base are belong to us.</p>

  <p>Ascii gcc grep int flood kilo linux access mailbomb hash *.* fork semaphore frack else win bar ssh Leslie Lamport. Man pages strlen cache gnu segfault tarball race condition perl packet sniffer root cookie private chown d00dz January 1, 1970. Rsa public crack bit warez throw for void concurrently ip mutex.</p>
</main>

  • Sehr schöne reine CSS-Lösung.

    – xela84

    24. Januar 2019 um 14:30 Uhr

  • Ich kann nicht glauben, dass es so gut funktioniert hat, vielen Dank!

    – Agu V

    26. August 2019 um 14:47 Uhr

Der folgende Code ergibt einen reibungslosen Bildlauf zum Anfang des Elements mit einem Offset für den festen Header:

var topOfElement = document.querySelector('#targetElement').offsetTop - XX;
window.scroll({ top: topOfElement, behavior: "smooth" });

Wobei XX die Höhe Ihres festen Headers ist.

  • Ein Tag für mich gerettet! Ich benutzte mat-card-content als meine scrollbare Arie mit a mat-toolbar als mein fester Header. ich benutzte ngx-scroll-to für mein Scrollen, aber es hat auf dem Handy nicht funktioniert. Ihre Lösung funktionierte jedoch mobil, aber nicht eigenständig, während das erwähnte Paket umgekehrt funktionierte. Kombiniert beides und Voila! DANKE!

    – imans77

    4. Februar 2019 um 20:37 Uhr

  • sollte wahrscheinlich die richtige/akzeptierte Antwort sein. Vielen Dank!

    – Generaldeep

    5. August 2020 um 16:16 Uhr

  • Dies war die einzige Lösung, die für meinen speziellen Fall funktionierte. Vielen Dank.

    – Wortumsteller

    16. Februar 2021 um 1:26 Uhr

Benutzer-Avatar
Arje Eidelmann

scroll-margin-top: $header-height;

Für moderne Browser: Setzen Sie die scroll-margin-top css-Eigenschaft auf den gewünschten oberen Offset für Elemente, die Sie verknüpfen/zu denen Sie scrollen. (Es hätte wahrscheinlich scroll-offset-top heißen sollen.)

* {
  scroll-margin-top: 100px;
}

DokumenteFunktioniert in modernen BrowsernCodepen-Demo

links = [...document.getElementsByClassName("js-link")]
links.forEach(element => {
  element.addEventListener("click", e => {
    e.preventDefault()
    document.getElementById(e.target.dataset.target).scrollIntoView({
      behavior: "smooth",
      block: "start",
      inline: "nearest"
    })
  })
})
body {
  margin: 0;
}

header {
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  height: 100px;
  background: #eee;
  display: flex;
  align-items: center;
}

header a {
  padding: 0.5em;
}

h1 {
  padding: 0.7em;
}

* {
  scroll-margin-top: 100px;
}

p {
  padding: 1em;
}
<header>
  <h1>page title</h1>
  <nav>
    <a href="#p1" class="js-link" data-target="p1">1</a>
    <a href="#p2" class="js-link" data-target="p2">2</a>
    <a href="#p3" class="js-link" data-target="p3">3</a>
    <a href="#p4" class="js-link" data-target="p4">4</a>
    <a href="#p5" class="js-link" data-target="p5">5</a>
  </nav>
</header>

<main>
  <p id="p1">
    paragraph 1.
    <br> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsu
  </p>
  <p id="p2">
    paragraph 2.
    <br> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsu
  </p>
  <p id="p3">
    paragraph 3.
    <br> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsu
  </p>
  <p id="p4">
    paragraph 4.
    <br> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsu
  </p>
  <p id="p5">
    paragraph 5.
    <br> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsu
  </p>
</main>

Benutzer-Avatar
Dipolmoment

Versuche Folgendes. Es funktioniert gut für mich:

  const headerHeight = 50; /* PUT HEADER HEIGHT HERE */
  const buffer = 25; /* MAY NOT BE NEEDED */
  const scrollToEl = document.querySelector("#YOUR-ELEMENT-SELECTOR");

  const topOfElement = window.pageYOffset + scrollToEl.getBoundingClientRect().top - headerHeight - buffer;
  window.scroll({ top: topOfElement, behavior: "smooth" });

Eine großartige einfache Lösung (inspiriert von Sanyam Jains Kommentar) ist die Verwendung {block: 'center'} um die Auswahl wie folgt vertikal zu zentrieren:

scrollIntoView({block: 'center'})

Bearbeiten – Ich habe leider auf der MDN-Seite festgestellt, dass diese Funktion “experimentell ist – sollte nicht in der Produktion verwendet werden”. Außerdem unterstützt IE es nicht (falls erforderlich).

Geben Sie hier die Bildbeschreibung ein

Benutzer-Avatar
Gemeinschaft

Wenn jemand Probleme damit hat, dass der obere Rand Ihres Container-Div nach einem scrollIntoView ignoriert wird, dann führen Sie einfach ein scrollTop relativ zu seinem übergeordneten Scroll-Container aus, anstatt Ihr Element in die Ansicht zu scrollen:

var topOfElementToView= $('#elementToScroll').position().top;
$('#parentScrollingContainer').scrollTop(topOfElementToView);

Habe die Antwort von user113716 in diesem Thread erhalten: Wie gehe ich zu einem bestimmten Element auf der Seite?

  • Geht davon aus, dass jquery verfügbar ist.

    – John Mei

    12. Oktober 2017 um 23:02 Uhr

1216340cookie-checkVerwenden von scrollIntoView mit einer Kopfzeile mit fester Position

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy