SVG 文档中的 HTML 按钮

Ond*_*era 7 html svg google-chrome

我有以下问题我想在 SVG 文档中动态创建 HTML 按钮。首先我查看SVG文档,找到合适的reactangle并用<foreignObject>元素替换矩形。我能够生成以下 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>
Run Code Online (Sandbox Code Playgroud)

这是我如何创建元素的片段

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);
Run Code Online (Sandbox Code Playgroud)

我有两个问题,尤其是在 Chrome 浏览器中:

  1. 元素<body>没有填充高度<foreignObject>
  2. button没有表现为一个按钮(鼠标悬停和鼠标按下无反应)(看来,这是固定在Chrome和Firefox浏览器的新版本)

JSFiddle在这里

sch*_*ebe 1

我不知道你为什么说<body>元素没有填满高度<foreignObject>!?

当我在 2020 年尝试时,我在屏幕上只看到中间有一个按钮。

我添加了一个<rect>具有相同大小(宽度和高度)的 SVG 元素,以便<foreignObject>可以比较这两个对象。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
  xmlns="http://www.w3.org/2000/svg"
  version="2.0"
  width="100%"
  height="100%"
  viewBox="0 0 90 50"
  >

<g transform="translate(1 0)">
    <foreignObject xmlns="http://www.w3.org/2000/svg" x="0" y="0" width="80" height="20">
        <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>
    <rect x="0" y="25" width="80" height="20" stroke="orange" stroke-width="2" fill="white"/>
</g>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它们的大小相同!

在此输入图像描述

我放了一张图片来证明我所说的,因为一年后我写的有可能是假的!