【问题标题】:Microsoft Edge can not set data attribute on SVGMicrosoft Edge 无法在 SVG 上设置数据属性
【发布时间】:2017-12-15 08:07:27
【问题描述】:

只是遇到了我没想到的事情。在 IE Edge 中测试网站,控制台报错:

无法设置未定义或空引用的属性“形状”

经过一段时间的调试,Microsoft Edge 似乎无法使用数据集在 SVG 元素上设置数据属性。我做了一个简化的测试用例:

https://codepen.io/freemagee/pen/YQRowd

Codepen 上有一个 SVG,然后我尝试使用数据集向它添加一些数据属性。当我在 Microsoft Edge 中查看该 codepen 时,我收到控制台错误。

Codepen sn-ps

HTML

<svg version="1.1" id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="50px" height="50px" viewBox="0 0 50 50">
  <rect id="square" width="50" height="50" stroke="red" stroke-width="2px" fill="transparent" />
</svg>

JS

function setSvgData() {
  var svg = document.getElementById('svg');

  svg.dataset.shape = 'square';
  svg.dataset.emotion = 'gloomy';
}

setSvgData();

阅读了SVGElement.dataset 我不确定现在该怎么做才能解决这个问题。如果可能的话,我想避免用 setAttribute 重写我所有的数据集代码。

有人遇到过这种情况或知道如何解决吗?

【问题讨论】:

标签: javascript html svg internet-explorer-11 microsoft-edge


【解决方案1】:

我已经为将来遇到此问题的人进行了基本功能测试。

https://codepen.io/freemagee/pen/QgoNJz

基本上,SVG 是动态创建的,数据集是在 try/catch 中操作的。

var hasSvgDatasetSupport = supportSvgDataset();

function supportSvgDataset() {
  var doesSupport = true;
  var testSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

  try {
    testSvg.dataset.shape = 'vector';
  } catch (error) {
    doesSupport = false;
  }

  return doesSupport;
}

// Example usage

var el = document.getElementById('shape');

if (hasSvgDatasetSupport) {
  el.dataset.mood = 'happy';
} else {
  el.setAttribute('data-mood', 'unhappy');
}

我不够聪明,无法进行适当的 polyfill,但这让一个在 Microsoft Edge 中失败的网站完全正常工作。

【讨论】:

  • 您的解决方案有效,但为什么不总是使用适用于所有浏览器的 setAttribute?除了语法之外,使用数据集没有直接优势。
  • @Ferdy,你是对的。使用 setAttribute 可以缓解整个情况。但是这个场景是在测试中出现的,数据集主要用于那个项目。
【解决方案2】:

'Fixed, Not yet flight' 的状态存在问题: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8489259/

与此同时,为了向后兼容,使用getAttributesetAttribute 代替dataset 似乎是要走的路。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 2019-11-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多