我有一个垂直长的SVG图像,我需要滚动到具有特定id的特定元素。
const el = document.getElementById(id);
el.scrollIntoView({
behavior: 'smooth',
block: 'center'
});这在chrome中很好,但是Firefox会滚动到SVG文件的顶部,而不是选定的元素。
我在一次堆栈闪电战中复制了这个错误:
https://stackblitz.com/edit/react-wkoiwq
https://react-wkoiwq.stackblitz.io
在chrome中,#热板元素被移动到中间,而在firefox中,SVG的顶部被移动到中间。
尝试更改center,使用start和end来查看效果。
有办法解决/避免这个问题吗?
发布于 2019-08-26 13:34:50
也许手工操作是正确的解决方案:
el.getBoundingClientRect().top获取相对于视图端口的位置。window.pageYOffset以获取当前的视口偏移量。document.clientHeight (没有滚动条)window.scrollTo滚动。例如:
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'});发布于 2019-08-27 07:02:28
我认为主要的问题是Firefox动画到了元素#热板的原始位置,这是父SVG的边界。Firefox不考虑y属性。
为了克服这一问题,您可以将svg代码包装在容器中,并添加与具有绝对位置的svg子元素具有相同位置的span。
您可以将HTML更改为:
<div class='container'>
<span id='hotplate-ref"></span>
<svg>.....</svg>
</div>然后添加到CSS中:
.container
{
position: relative;
}
#hotplate-ref
{
position: absolute;
top: 1703px; /* includes margin top of svg (1400px) + y attribute of svg element (503px) */
width: 0px;
height: 0px;
visibility: hidden;
pointer-events: none;
}最后将"componentDidMount()“改为:
const el = document.getElementById("hotplate-ref");
el.scrollIntoView({
behavior: 'smooth',
block: 'start'
});我在Chrome和FF中测试了代码,它运行得很好。
显然,您也可以使用其他svg子元素来完成这个任务。
https://stackoverflow.com/questions/57610098
复制相似问题