【发布时间】:2015-02-06 21:58:40
【问题描述】:
我正在使用 JavaScript 生成动态 SVG 图像。 我的目的是让特定区域的信息包含在工具提示中。 到目前为止,我在 Chrome 和 Firefox 中都可以使用,但在 IE 11 中只能部分使用。
如果我使用 textContent,"\r\n" 在 IE 中会被忽略,<br /> 会按字面意思显示。
innerHTML 似乎是先前提出的类似问题的答案:
Question 9330671
Question 9980416
通常,切换到 innerHTML 可以解决这个问题,但 IE 不支持 innerHTML 用于这种特殊用途,因此根本不会显示任何文本。
使用 innerHTML 或 textContent 适用于 Chrome 或 Firefox,因此,这只是 IE 中的一个问题(使用 IE 11 测试)。对在测试提供的代码时必须使用此浏览器的任何人表示歉意。
可在http://jsfiddle.net/rnhy9pus/ 获取交互式代码。
或者,完整的代码包含在下面:
function createPathContent(svgID, popupText, pathDirections)
{
var path = document.createElementNS("http://www.w3.org/2000/svg","path");
path.setAttribute("d",pathDirections);
var popup = document.createElementNS("http://www.w3.org/2000/svg","title");
popup.textContent = popupText; // <-- LINE TO FOCUS ON
path.appendChild(popup);
document.getElementById(svgID).appendChild(path);
}
function createPathHTML(svgID, popupText, pathDirections)
{
var path = document.createElementNS("http://www.w3.org/2000/svg","path");
path.setAttribute("d",pathDirections);
var popup = document.createElementNS("http://www.w3.org/2000/svg","title");
popup.innerHTML = popupText; // <-- LINE TO FOCUS ON
path.appendChild(popup);
document.getElementById(svgID).appendChild(path);
}
function createExample(svgID)
{
document.getElementById(svgID).setAttribute("xmlns", "http://www.w3.org/2000/svg");
document.getElementById(svgID).setAttribute("version", "1.1");
document.getElementById(svgID).setAttribute("width", "300");
document.getElementById(svgID).setAttribute("viewBox", "0 0 100 100");
document.getElementById(svgID).setAttribute("preserveAspectRatio", "xMinYMin meet");
var style = document.createElement("style");
style.setAttribute("type","text/css");
style.innerHTML = "path { fill: #ccc; } path:hover { fill: #ff0; }";
document.getElementById(svgID).appendChild(style);
var NEW_LINE = "\r\n";
//var NEW_LINE = "<br />"; // This displays literally in textContent and as a new line in innerHTML.
createPathContent(svgID, "Tooltip text using textContent:" + NEW_LINE + "New Line", "M 10 10 L 90 10 L 90 45 L 10 45 Z");
// Works correctly in Chrome or Firefox. Displays in IE 11, but only on a single line.
createPathHTML(svgID, "Tooltip text using innerHTML:" + NEW_LINE + "New Line", "M 10 55 L 90 55 L 90 90 L 10 90 Z");
// Works correctly in Chrome or Firefox. Does not display in IE 11.
}
createExample("exampleSVG");
<svg id="exampleSVG" xmlns="http://www.w3.org/2000/svg"></svg>
【问题讨论】:
标签: javascript internet-explorer svg newline innerhtml