使用 SVG 时 ScrollIntoView 在 Firefox 中出现 bug

gyc*_*gyc 5 javascript firefox cross-browser

我有一个垂直长的 SVG 图像,我需要滚动到具有特定 id 的某个特定元素。

const el = document.getElementById(id);
el.scrollIntoView({
  behavior: 'smooth',
  block: 'center'
});
Run Code Online (Sandbox Code Playgroud)

这在 Chrome 中效果很好,但 Firefox 会滚动到 SVG 文件的顶部,而不是所选元素的视图中。

我在 stackblitz 中重现了该错误:

https://stackblitz.com/edit/react-wkoiwq

https://react-wkoiwq.stackblitz.io

在 Chrome 中,#hotplate 元素移动到中心,而在 Firefox 中,SVG 的顶部移动到中心。

尝试更改center, 和startend查看效果。

有没有办法解决/避免这个问题?

Nic*_*lay 3

也许手动执行是正确的解决方案:

例如:

var el = document.getElementById("hotplate");

// { block: "top" } behavior:
let newScrollY = window.pageYOffset + el.getBoundingClientRect().top;

// adjust to behave like { block: "center" }
newScrollY = newScrollY - document.documentElement.clientHeight/2;

window.scrollTo({top: newScrollY, behavior: 'smooth'});
Run Code Online (Sandbox Code Playgroud)