我正在使用 NextJs。我想在我的标题部分创建一个链接。此链接应通过滚动将用户带到同一页面上的 TestimonialsSection。
<Link href={"#TestimonialsSection"}>
<a className={styles.Designation}>Mentor</a>
</Link>
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的代码,但没有成功。但 URL 发生了变化。提前致谢
小智 64
在普通 HTML 中你会做这样的事情
<a href="#first-section">My first section</a>
<a href="#second-section">My second section</a>
<div id="first-section">SECTION 1</div>
<main id="second-section">SECTION 2</main>
Run Code Online (Sandbox Code Playgroud)
在 NextJS 中你会得到类似的东西。您可以使用组件,而不是使用锚标记进行链接Link。
<Link href="#first-section">My first section</Link>
<Link href="#second-section">My second section</Link>
<div id="first-section">SECTION 1</div>
<main id="second-section">SECTION 2</main>
Run Code Online (Sandbox Code Playgroud)
这样就可以了。但是,如果您希望起始 URL 为www.my-site.com/#second-section,则需要将 Link 组件的scrollprop 设置为false。前任:
...
<Link href="#second-section" scroll={false}>My second section</Link>
...
Run Code Online (Sandbox Code Playgroud)
确保您的节/div,即目标元素已正确设置ID#属性,并且相应的锚链接具有ID名称#前缀
这是官方 NextJS 文档https://nextjs.org/docs/api-reference/next/link
希望这能解决您的问题。
小智 6
尝试一下这个解决方案,我正在使用 TypeScript,所以这个答案肯定适用于 TypeScript Next.js
export default function Home() {
// let's make a function that receive the specific element_id as string and scroll into that element_id
const scrolltoHash = function (element_id: string) {
const element = document.getElementById(element_id)
element?.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
}
return (
<div>
{/* attach that function with onClick event to an clickable element */}
<div onClick={() => scrolltoHash('contact')}>
<span>Click me to Scroll</span>
</div>
{/* ...imagine lot of sections/code here */}
<section id="contact">
{/* this is the section we want to scroll it could be any element not just limited to section but must have an unique ID. */}
</section>
{/* ...imagine lot of sections/code here */}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68367 次 |
| 最近记录: |