使用CSS定位SVG的x/y坐标在iOS设备上无效?

4
根据W3C的CSS/SVG样式指南(https://www.w3.org/TR/SVG2/styling.html),我应该能够使用x/y属性在CSS中定位特定的SVG元素。
这可以在Chrome和三星Galaxy S6上使用(没有尝试其他型号/浏览器)。然而,在iOS和某些我尝试过的窗口/HTC设备上不起作用。
这是我正在使用的代码(借助d3.js);
<!DOCTYPE html>
<html>

<head>
<meta name="viewport" content="width=device-width">
<meta name="viewport" content="initial-scale=1, maximum-scale=1.5">
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>

    <style>
        @media handheld,
        screen and (max-width: 425px) {
            foreignObject {
                x: 30;
                y: 30;
            }
        }
    </style>
</head>

<body>
    <script>
        d3.selectAll("body")
            .append("svg")
            .append("foreignObject")
            .attr("width", 30)
            .attr("height", 30)
            .attr('x', 0)
            .attr('y', 0)
            .html("hello")
    </script>
</body>

</html>

这是代码的plnk链接。
我想知道是否有任何解决方法?或者是否有人可以推荐另一种添加x/y响应式断点的方式?
谢谢。

你为什么有handheld?我认为它被iOS忽略了,并且被定义为<=320px。 - David Gilbertson
哦,另外,foreignObject在跨浏览器支持方面并不是很好。如果你的目标是良好的覆盖率,我会考虑放弃它(和handheld)。 - David Gilbertson
无法在Firefox 47/Ubuntu上工作,但可以在Chrome/Ubuntu上工作。 - Tim B
@DavidGilbertson 我尝试过删除 handheld,并将 foreignObject 更改为 rect,但不幸的是,在 iOS 上仍然存在相同的问题。 - alexc101
@TimB 感谢您在 Firefox 上进行测试 - 我修改了帖子,我不应该假设它在所有浏览器上都能正常工作,当时我只在 Chrome 上进行了测试。 - alexc101
1个回答

2
你所提到的功能是SVG 2。SVG 2仍处于工作草案阶段。浏览器供应商正在实现功能,但我不会在依赖SVG2功能的生产环境中使用它。甚至caniuse.com也没有引入“可以使用SVG 2”部分。他们正在这里讨论

现在来回答你的问题 :)

选项1

如果您只想移动整个SVG块到页面上,那么可以在响应式布局中使用HTML,并将SVG放在其中。例如:

  <div class="responsive-wrapper">
    <svg width="100%" height="200">
      <rect x="10" y="10" height="200" width="200"/>
    </svg>
  </div>
  <div class="responsive-wrapper">
    <svg width="100%" height="200">
      <rect x="10" y="10" height="200" width="200"/>
    </svg>
  </div>

那么

.responsive-wrapper {
  border: 1px dashed lightgray;
  width: 100%;
}

@media screen and (min-width: 500px) {
  .responsive-wrapper {
    float: left;
    width: 48%;
  }
}

rect {
  fill: steelblue;
}

选项二

https://jsbin.com/xesuma/1

JavaScript更加复杂,并且不易扩展。
<svg width="100%" height="200">
  <rect id="rect-1" x="10" y="10" height="200" width="200"/>
</svg>

还有一些像这样的恶心东西:

var rect1El = document.getElementById('rect-1');
var currentWidth = rect1El.getAttribute('width');

window.addEventListener('resize', function() {
  var newWidth = window.innerWidth > 400 ? 300 : 100;

  if (newWidth !== currentWidth) {
    rect1El.setAttribute('width', newWidth);
    currentWidth = newWidth;
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接