Window.scroll() 方法只在强制重新加载时有效,而在 Svelte 的 onMount() 中无效。

huangapple go评论111阅读模式
英文:

Window.scroll() method only working on hard reload, but not onMount() in Svelte

问题

我正在尝试在特定组件挂载时每次将窗口设置到特定位置。我在这里使用了 window.scroll()onMount() 处理程序:

  1. onMount(() => {
  2. window.scroll({
  3. top: 400,
  4. left: 100,
  5. behavior: "smooth",
  6. })
  7. })

问题是,该函数仅在我手动重新加载浏览器页面时才起作用,而在我实际导航到我的 SvelteKit 应用程序页面时却不起作用。

我修改了函数以指示 onMount 是否确实起作用:

  1. onMount(() => {
  2. window.scroll({
  3. top: 400,
  4. left: 100,
  5. behavior: "smooth",
  6. })
  7. console.log("页面已挂载!")
  8. })
  9. onDestroy(() => {
  10. console.log("页面已卸载!")
  11. })

console.log() 总是按预期工作,但 window.scroll() 不起作用。这里可能存在什么问题?

英文:

I am trying to set my window to a particular place everytime a particular component is mounted. I am using window.scroll() and onMount() handler for this.

  1. onMount(() => {
  2. window.scroll({
  3. top: 400,
  4. left: 100,
  5. behavior: "smooth",
  6. })
  7. })

The problem is that the function only works when I manually reload the page in the browser, and not when I actually navigate to the page in my sveltekit app.

I modified the function to indicate whether onMount is indeed working:

  1. onMount(() => {
  2. window.scroll({
  3. top: 400,
  4. left: 100,
  5. behavior: "smooth",
  6. })
  7. console.log("Page Mounted!")
  8. })
  9. onDestroy(() => {
  10. console.log("Page Unmounted!")
  11. })

console.log() always works as expected but not window.scroll(). What could be the problem here?

答案1

得分: 0

如评论中所提到的,将 window.scroll() 包装在 setTimeout() 中可以解决这个问题。

英文:

As mentioned in the comments, wrapping window.scroll() in a setTimeout() fixed this issue.

huangapple
  • 本文由 发表于 2023年7月6日 13:31:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625758.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定