代码之家  ›  专栏  ›  技术社区  ›  ccprog

Safari不适用于外来对象

  •  3
  • ccprog  · 技术社区  · 6 年前

    下面是Safari的一个奇怪的、明显有bug的行为(使用版本11和12进行了测试)。A <foreignObject> 包含HTML,当缩放时,仍然以其原始大小显示,即使其本地用户空间坐标根据屏幕缩放。HTML内容将明显溢出父级 <svg> ,甚至违反显式CSS规则。

    the width and height need to be set explicitly (我用百分比和绝对单位进行了测试)和 namespace should be set (我把它放在 <

    奇怪的是,dev工具以预期的缩放大小显示标记矩形(浏览器窗口中的覆盖),而报告的大小数字是未缩放的。

    以下是预期设置:

    svg, foreignObject {
      overflow: hidden;
    }
    rect {
      fill:yellow;
    }
    #content {
      position: relative;
      width: 100%;
      height: 100%;
      background: red;
      border-radius: 50%;
    }
    <svg width="200px" height="200px" viewBox="0 0 400 400">
      <rect width="100%" height="100%" />
      <foreignObject width="400" height="400">
        <div id="content" xmlns="http://www.w3.org/1999/xhtml"></div>
      </foreignObject>
    </svg>

    Safari截图:

    enter image description here

    <g> )而不是通过viewBox隐式缩放没有什么区别。此外,我还研究了绝对和相对大小的所有组合

    有人知道如何绕过这个问题吗?

    0 回复  |  直到 6 年前
        1
  •  3
  •   do-ic    5 年前

    这似乎与 webkit bug 23113 transform: scale(${scale}) (必须使用JS获取当前比例)属性 <section> 里面 foreignObject (例如 marpit-svg-polyfill )

        2
  •  0
  •   Petr KlimeÅ¡    5 年前

    if (window['safari'] !== undefined) {
        const svgContainerElement = document.getElementById('svgContainer');
        const svgElement = document.getElementById('svg');
    
        const zoomLevel = svgContainerElement.clientWidth / 867; // width of the foreign object
        svgElement.style.transform = `scale(${zoomLevel})`;
    
        const leftOffset = svgContainerElement.getBoundingClientRect().left - 
        svgElement.getBoundingClientRect().left;
        const topOffset = svgContainerElement.getBoundingClientRect().top - 
    svgElement.getBoundingClientRect().top;
    
        svgElement.style.position = `relative`;
        svgElement.style.left = leftOffset;
        svgElement.style.top = topOffset;
    }
    

    如果浏览器无法正确响应样式更改,则可能会强制您重新绘制svg:

    const parent = svgElement.parentElement;
    if (parent) {
        parent.removeChild(el);
        parent.appendChild(el);
    }
    

    这个问题可能晚了几年,但我希望它能帮助一些人,因为这是safari到现在(2019年11月)的一个问题