Tengo curiosidad por saber cómo puedo desplazar el elemento de identificación de destino del href de una etiqueta de anclaje al centro de la página usando el método scrollIntoView.
Aquí está mi código hasta ahora:
$("a").click(function () { var target = $($(this).attr("href")); target[0].scrollIntoView({ behavior: "smooth", block: "center" }) });Puedo registrar el elemento objetivo en la consola y usar otros métodos para cambiar el elemento objetivo, pero no sé cómo centrarlo cuando me desplazo.
Aquí hay un Codepen con un ejemplo de lo que me gustaría hacer, pero en su lugar usa scroll-margin-top: 50vh .
Cualquier cosa es apreciada, Thx.
Su código parece estar funcionando para mí. El problema puede ser que href no sea un selector css válido o que el elemento no esté disponible en el alcance de su código.
Intente agregar console.log(target) a la función de devolución de llamada, o incluso registrar target[0] y ver si es el objetivo deseado.
aquí hay un fragmento de trabajo de .scrollIntoView
(async () => { const $ = str => document.querySelector(str); const wait = t => new Promise(r => setTimeout(r, t)); const section1 = $("section"); const section2 = $("section:nth-of-type(3)"); const options = { behavior: "smooth", block: "center" } while (true) { await wait(3000); section2.scrollIntoView(options); await wait(3000); section1.scrollIntoView(options); } })(); body { margin: 0; height: 300vh; background: linear-gradient(black, lightgray); display: flex; flex-direction: column; justify-content: space-between; align-items: center; } section { height: 20px; width: 100%; background-color: rgba(30, 30, 255, 0.8); } <section></section> <section></section> <section></section> <section></section> <section></section>