【发布时间】:2016-12-09 23:11:17
【问题描述】:
我正在尝试在 AngularJS 指令中向 SVG 文件添加一个按钮。我的问题是按钮文本没有出现。这是我的代码:
function makeElement(namespace, tag, attrs) {
var el= document.createElementNS(namespace, tag);
for (var k in attrs)
el.setAttribute(k, attrs[k]);
return el;
}
angular.module('SvgApp').directive('svgFile', ['$compile', function ($compile) {
return {
restrict: 'A',
templateUrl: 'img/file.svg',
link: function (scope, element, attrs) {
var svgNamespace = 'http://www.w3.org/2000/svg';
var htmlNamespace = 'http://www.w3.org/1999/xhtml';
var result = makeElement(svgNamespace, "foreignObject",{"class":"point","xmlns":"http://www.w3.org/2000/svg","x":"100","y":"100","width":"300","height":"150"});
var body = document.createElement("body");
body.setAttribute("xmlns", htmlNamespace);
body.setAttribute("style", "margin: 0px; height: 100%;");
var btn = makeElement(htmlNamespace, "button", {"id":"rect3537","type":"button","style":"width:100%; height:100%;","class":"button"});
var btnSvg = makeElement(htmlNamespace, "svg", {"xmlns":"http://www.w3.org/2000/svg","version":"1.1","width":"100%","height":"100%","viewBox":"0 0 50 25"});
var btnText = makeElement(svgNamespace, "text",{"y":"75%","x":"50%","text-anchor":"middle","font-size":"20","fill":"white"});
var textNode = document.createTextNode("text");
btnText.appendChild(textNode);
btnSvg.appendChild(btnText);
btn.appendChild(btnSvg);
body.appendChild(btn);
result.appendChild(body);
console.log(result);
document.getElementById("svg-wrapper").appendChild(result);
}
}
}]);
文件.svg
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
width="100%"
height="100%"
id="svg-wrapper">
</svg>
结果变量的值:
<foreignObject class="point" xmlns="http://www.w3.org/2000/svg" x="100.0000000000000" y="100.0000000000000" width="300" height="150">
<body xmlns="http://www.w3.org/1999/xhtml" style="margin: 0px; height: 100%;">
<button id="rect3537" type="button" style="width:100%; height:100%;" class="btn btn-primary ng-scope">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewbox="0 0 50 25">
<text y="75%" x="50%" text-anchor="middle" font-size="20" fill="white">text</text>
</svg>
</button>
</body>
</foreignObject>
我不知道为什么它只显示没有文字的空按钮。在 Chrome 52 和 Firefox 48 上测试。
【问题讨论】:
标签: javascript angularjs svg