简体   繁体   English

如何使用jQuery将href的scrollIntoView目标id元素滚动到页面中心

[英]How to scrollIntoView target id element of href to center of page using jQuery

I am curious how I can scroll the target id element of an anchor tag's href to the center of the page using the scrollIntoView method.我很好奇如何使用 scrollIntoView 方法将锚标记的 href 的目标 id 元素滚动到页面的中心。

Here is my code so far:到目前为止,这是我的代码:

$("a").click(function () {
    var target = $($(this).attr("href"));
  
    target[0].scrollIntoView({
      behavior: "smooth", 
      block: "center"
    })
  });

I am able to log the targeted element to the console and use other methods to change the targeted element but can't figure out how to center it when scrolling.我能够将目标元素记录到控制台并使用其他方法来更改目标元素,但无法弄清楚如何在滚动时将其居中。

Here is a Codepen with an example of what I'd like to do but instead uses scroll-margin-top: 50vh .这是一个Codepen,其中包含我想做的示例,但使用scroll-margin-top: 50vh

Anything is appreciated, Thx.任何东西都值得赞赏,Thx。

Your code seems to be working for me.您的代码似乎对我有用。 The issue may be with the href not being a valid css selector or the element not being available in the scope of your code.问题可能在于 href 不是有效的 css 选择器或元素在您的代码范围内不可用。

Try adding console.log(target) to the callback function, or even logging target[0] and seeing if it is the desired target.尝试将console.log(target)添加到回调函数中,甚至记录target[0]并查看它是否是所需的目标。

here is a working snippet of .scrollIntoView这是.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM