【问题标题】:SVG onclick event not firing on iOS devicesSVG onclick 事件未在 iOS 设备上触发
【发布时间】:2019-08-18 14:20:01
【问题描述】:

我有一个带有 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

【问题讨论】:

    标签: javascript ios svg onclick


    【解决方案1】:

    是的,很遗憾,iOS 中存在一个错误 - “click”和“tap”事件在 svg 标记中不起作用。

    但您可以使用“touchstart”/“touchend”事件——它们在带有 svg 的 iOS 中运行良好。

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

    【讨论】:

      【解决方案2】:

      您必须明确调用getElementById() 作为document 的方法:

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

      【讨论】:

      • 如果它到处都坏了我会更早发现它,但因为它只出现在我正在测试的触摸设备上,我完全错过了明显的!
      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2014-02-07
        • 1970-01-01
        • 2021-09-28
        • 2014-05-07
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        • 2014-06-25
        • 2014-08-11
        相关资源
        最近更新 更多