【问题标题】:Position sticky SVG element contained inside div with overflow将包含在 div 中的粘性 SVG 元素定位为溢出
【发布时间】:2019-10-16 22:34:14
【问题描述】:

有没有办法在 SVG 中使用position: sticky?类似于 this 示例的工作方式。

为了使事情稍微复杂化,我希望在另一个 divoverflow:auto 内的 SVG 元素内使用 position: sticky。我创建了一个示例,说明我在 this codesandbox 中尝试实现的目标。

编辑 1: 不确定这是否会有所不同,但对于我自己的应用程序中的上下文,我使用 react 和 react-redux 来包含/排除形状以形成图形。要求是在滚动时将某些元素保留在视口的顶部,就像您要冻结标题/行时 Excel 一样。

编辑 2:更新沙箱以包含答案代码

【问题讨论】:

    标签: reactjs svg react-redux


    【解决方案1】:

    没有。 position 是一个仅适用于 HTML 元素的属性。它在 SVG 中无效。

    您需要使用 Javascript。添加一个 onscroll 事件处理程序来观察滚动并重新定位 SVG 元素。

    window.addEventListener("scroll", function(evt) {
    
      document.getElementById("sticky-rect").setAttribute("y", screenYtoSVGUnits(window.scrollY) + 10);
    
    });
    
    
    // Converts a screen Y position to SVG units which have a viewBox transform
    function screenYtoSVGUnits(val) {
      const svg = document.getElementById("mysvg");
      let pt = svg.createSVGPoint();
      pt.x = 0;
      pt.y = val;
      pt = pt.matrixTransform(svg.getCTM().inverse());
      return pt.y;
    }
    <svg id="mysvg" viewBox="0 0 100 500">
      <line x1="0" y1="0" x2="100" y2="500" stroke="black" stroke-width="1"/>
      <rect id="sticky-rect" x="0" y="10" width="100" height="10" fill="red"/>
    </svg>

    【讨论】:

    • 发布问题后,我实际上开始研究这种解决方案作为替代解决方案。感谢您的帮助。
    猜你喜欢
    • 2023-03-16
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    相关资源
    最近更新 更多