我正在使用JavaScript生成动态SVG图像。
我的意图是让特定区域的信息包含在工具提示中。
到目前为止,我已经在Chrome和Firefox中成功实现,但在IE 11中仅部分成功。
如果我使用textContent,在IE中会忽略"\r\n",并且"
"会被显示出来。
先前提问过类似问题的答案似乎是使用innerHTML: Question 9330671 Question 9980416 通常情况下,切换到innerHTML就可以解决这个问题,但是IE不支持此特定用途的innerHTML,因此根本没有文本显示。
使用innerHTML或者textContent对于Chrome或Firefox都有效,所以这只是IE(测试过IE 11)中的问题。抱歉对于那些必须使用IE进行代码测试的人们。
如果我使用textContent,在IE中会忽略"\r\n",并且"
"会被显示出来。
先前提问过类似问题的答案似乎是使用innerHTML: Question 9330671 Question 9980416 通常情况下,切换到innerHTML就可以解决这个问题,但是IE不支持此特定用途的innerHTML,因此根本没有文本显示。
使用innerHTML或者textContent对于Chrome或Firefox都有效,所以这只是IE(测试过IE 11)中的问题。抱歉对于那些必须使用IE进行代码测试的人们。
交互式代码可在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>