gpt4 book ai didi

javascript - 修复垂直滚动时的 SVG 元素,Firefox 的问题

转载 作者:行者123 更新时间:2023-11-29 23:19:49 25 4
gpt4 key购买 nike

当尝试在可滚动的 div 中垂直固定 SVG 项目时,将其 y 坐标设置为 scrollTop 属性,如以下示例所示:

var container = document.getElementById('container');
var fixedText = document.getElementById('fixed-text');
fixedText.setAttribute('y', container.scrollTop + 50);
container.addEventListener('scroll', function() {
fixedText.setAttribute('y', container.scrollTop + 50);
});
    div {
border: 1px solid black;
width: 300px;
height: 300px;
margin: auto;
overflow: auto;
}
svg {
width: 400px;
height: 2000px;
}
text {
text-anchor: middle;
}
  <div id="container">
<svg>
<text id="fixed-text" x="200" y="50">Fixed text vertically, but not horizontally</text>
</svg>
</div>

JSFiddle:https://jsfiddle.net/fr4top2g/10/

SVG 项目已在 Chrome 中正确修复,但我在使用 Firefox 时遇到问题,该项目似乎在更新 div 内的 View 框之前定位,导致它在屏幕上振荡,而不是固定为预期的。 (这在使用鼠标滚轮滚动时尤为明显)。

这个问题可能是由 Chrome 和 Firefox 中不同的滚动处理方式引起的,您有什么简单的解决方案吗?

注意 1:由于该项目可能太宽而无法放入 div,因此它还必须是可水平滚动的,这意味着如果解决方案不涉及将 SVG 项目从其容器可滚动 div 中取出会更简单.

注2:请注意,如果我们在Firefox中打开网络控制台,点击SVG项目,然后用鼠标滚轮垂直滚动,这个问题似乎由于某种原因得到了解决。

注意 3:我已经在这个项目中使用 D3.js,所以任何涉及它的解决方案都不会打扰我。我目前没有使用 JQuery,尽管如果我不得不这样做也是可能的。

注4:同样的问题出现在提供给这个主题的解决方案中:Fixing an element on Y axis, but scrolling with page on x axis?

提前感谢您的帮助。

最佳答案

Firefox 滚动管理与 DOM 元素更新异步完成,如本页所述:https://developer.mozilla.org/en-US/docs/Mozilla/Performance/Scroll-linked_effects

我终于设法修复了 SVG 项目,没有使用 Javascript,而是使用了一些 CSS,以及一个 SVG 外部对象:

    #container {
border: 1px solid black;
width: 300px;
height: 300px;
margin: auto;
overflow: auto;
}
svg#outer-svg {
width: 400px;
height: 2000px;
}
text {
text-anchor: middle;
}
#inner-svg {
position: sticky;
top: 70px;
width: 400px;
height: 50px;
}
    <div id="container">
<svg id="outer-svg">
<foreignObject id="foreign-object" width="100%" height="100%">
<body xmlns="http://www.w3.org/1999/xhtml">
<svg id="inner-svg">
<text x="200" y="30">Fixed text vertically, but not horizontally</text>
</svg>
</body>
</foreignObject>
</svg>
</div>

关于javascript - 修复垂直滚动时的 SVG 元素,Firefox 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51140165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com