SVG onclick事件未在iOS设备上触发

时间:2019-03-27 21:47:57

标签: javascript ios svg onclick

我有一个带有rect子元素的SVG。 rect子有一个onclick事件,该事件通过其ID获取另一个元素并更改其背景颜色。这可以在台式机上的Chrome以及Chrome检查器中的iOS模拟器中使用。但是,它不会在iOS设备上触发事件。

在台式机和iOS设备上都可以更改代码中的哪些内容?我应该听其他活动吗?

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" style="height: 200px; width: 200px; border: 4px dashed salmon;">
    <rect x="25" y="25" height="50" width="50" style="cursor: pointer; fill: gold;" onclick="getElementById('box').style.backgroundColor = 'gold';"></rect>
</svg>
<div id="box" style="height: 200px; width: 200px; background-color: skyblue;"></div>

这里是CodePen

3 个答案:

答案 0 :(得分:1)

是的,很不幸,iOS中存在一个错误-“点击”和“点击”事件在svg标签中不起作用。

但是您可以使用“ touchstart” /“ touchend”事件-它们在带有svg的iOS中效果很好。

您可以模拟“点击”事件: https://stackoverflow.com/a/32120668/3265404

答案 1 :(得分:0)

您必须显式调用getElementById()作为document的方法:

onclick="document.getElementById('box').style.backgroundColor = 'gold';"

答案 2 :(得分:0)

我在iOS上的Chrome上遇到了这个问题,发现在svg元素上使用cursor: pointer;可以使其正常工作。

来源:https://github.com/meteor/meteor/issues/681#issuecomment-351443900

相关问题