【发布时间】:2013-07-02 12:07:14
【问题描述】:
我有以下问题我想在 SVG 文档中动态创建 HTML 按钮。首先,我查看了 SVG 文档,找到了合适的反应角度并将矩形替换为 <foreignObject>element。我能够生成以下 SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
version="1.1"
width="100%"
height="100%"
viewBox="0 0 93.875076 43.283451"
id="svg20755"
xml:space="preserve">
<g id="Button-1" transform="translate(0.5000775,0.50220189)">
<foreignObject xmlns="http://www.w3.org/2000/svg" x="0" y="0" width="93" height="43">
<body xmlns="http://www.w3.org/1999/xhtml" style="margin: 0px; height: 100%;">
<button type="button" style="width:100%; height:100%;" onclick="alert('Button clicked')">
Juhuhuhu!
</button>
</body>
</foreignObject>
</g>
</svg>
这是我创建元素的 sn-p 方式
var ns_HTML = 'http://www.w3.org/1999/xhtml';
var ns_SVG = REX.HELPERS.ns_svg;
var element = <Some code to load an SVG element>
var foreignObject = document.createElementNS(ns_SVG, 'foreignObject');
var body = document.createElementNS(ns_HTML, 'body');
body.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); // FF
body.style.margin = '0px';
body.style.height = '100%';
var button = document.createElementNS(ns_HTML, 'button');
button.setAttribute('type','button');
button.setAttribute('style','width:100%; height:100%;');
button.innerHTML = 'Test!';
body.appendChild(button);
foreignObject.appendChild(body);
我有两个问题,尤其是在 Chrome 浏览器中:
- 元素
<body>没有填满<foreignObject>的高度 -
(这似乎已在 Chrome 和 Firefox 的新版本中得到修复)button没有像按钮一样工作(鼠标悬停和鼠标按下时没有反应)
JSFiddle here
【问题讨论】:
-
仅供参考,我尝试将显式
-webkit-appearance: button添加到@style,但没有任何改变。 -
同样
appearance: push-button;不起作用 -
感谢这个问题。这是我读到的第一个关于包含 HMTL 元素的 SVG 文件的问题。
标签: html google-chrome svg