Safari foreignObject getBBox错误

时间:2019-06-29 20:40:28

标签: svg safari

在Safari中,foreignObject元素的getBBox始终对x返回0,对于y返回0。请参阅以下example(在野生动物园中打开)。通知console.log(document.querySelector('foreignObject').getBBox()); 打印

{
  height: 100,
  width: 100,
  x: 0,
  y: 0
}

在chrome和firefox中,它可以按预期工作。 有没有解决此问题的方法?

1 个答案:

答案 0 :(得分:2)

将foreignObject包裹在<g>中,并获得包装器的边界框。

console.log(document.querySelector('.foreignObjectWrapper').getBBox());
console.log(document.querySelector('#rect').getBBox());
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
   <svg viewBox="0 0 200 200" style="height: 200px; width: 200px;" xmlns="http://www.w3.org/2000/svg">
    <rect width="100%" height="100%" fill="red"/>
    <rect id="rect" x="50" y="50" width="100" height="100" fill="green"/>
     <g class="foreignObjectWrapper">
    <foreignObject x="50" y="50" width="100" height="100">
      <div style="background-color: yellow; width: 100px; height:100px;">
      </div>
    </foreignObject>
     </g>
  </svg>
</body>
</html>