【问题标题】:ScrollIntoView bugged in firefox when using SVG使用 SVG 时 ScrollIntoView 在 Firefox 中出现问题
【发布时间】:2019-12-27 19:45:08
【问题描述】:

我有一个垂直长的 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 中,#hotplate 元素被移动到中心,而在 Firefox 中,SVG 的顶部被移动到中心。

尝试更改center,用startend 看看效果。

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

【问题讨论】:

    标签: javascript firefox cross-browser


    【解决方案1】:

    也许手动操作是正确的解决方案:

    例如:

    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'});
    

    【讨论】:

      【解决方案2】:

      我认为主要问题是 Firefox 动画到元素 #hotplate 的原始位置,该位置是父 SVG 的边界。 Firefox 不考虑 y 属性。

      要克服这个问题,您可以将 svg 代码包装在一个容器中,并添加一个与 svg 子元素具有相同位置且具有绝对位置的跨度。

      您可以将 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 子元素执行此操作。

      【讨论】:

        猜你喜欢
        • 2011-08-22
        • 2017-08-23
        • 2014-06-24
        • 2022-01-13
        • 2018-02-26
        • 1970-01-01
        • 2014-09-18
        • 2020-06-06
        • 2011-06-25
        相关资源
        最近更新 更多