Skip to content

Instantly share code, notes, and snippets.

@ufologist
Created August 26, 2015 04:46
Show Gist options
  • Save ufologist/f078426192fd92f7ac31 to your computer and use it in GitHub Desktop.
Save ufologist/f078426192fd92f7ac31 to your computer and use it in GitHub Desktop.
svg.innerHTML workaround
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>svg.innerHTML workaround</title>
</head>
<body>
<div>
<button onclick="innerHTMLNormal()">svg.innerHTML</button>
<button onclick="innerHTMLWorkaround()">svg.innerHTML workaround</button>
</div>
<div id="svgContainer"></div>
<script>
var svgContent = '<circle cx="20" cy="20" r="10" stroke="black" stroke-width="2" fill="red"></circle><circle cx="50" cy="20" r="10" stroke="black" stroke-width="2" fill="green"></circle>';
function newSvgEl() {
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svg.setAttribute('version', '1.1');
svg.setAttribute('width', '200');
svg.setAttribute('height', '200');
return svg;
}
function innerHTMLNormal() {
var svgEl = newSvgEl();
svgEl.innerHTML = svgContent;
document.getElementById('svgContainer').innerHTML = '';
document.getElementById('svgContainer').appendChild(svgEl);
}
function innerHTMLWorkaround() {
var svgEl = newSvgEl();
// 移动端浏览器没有给 SVG 提供 innerHTML 功能
if (svgEl.innerHTML != undefined) {
svgEl.innerHTML = svgContent;
} else {
// Create a dummy receptacle
var dummy = document.createElement('div');
// Wrap the svg string to a svg object (string)
// Add all svg to the receptacle
dummy.innerHTML = '<svg>' + svgContent + '</svg>';
// Splice the childs of the SVG inside the receptacle to the SVG at the body
var svgChildNodes = dummy.childNodes[0].childNodes;
for (var i = 0, length = svgChildNodes.length; i < length; i++) {
svgEl.appendChild(svgChildNodes[i]);
}
}
document.getElementById('svgContainer').innerHTML = '';
document.getElementById('svgContainer').appendChild(svgEl);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment