gpt4 book ai didi

SVG 文档中的 HTML 按钮

转载 作者:行者123 更新时间:2023-12-02 11:19:39 28 4
gpt4 key购买 nike

我有以下问题我想在 SVG 文档中动态创建 HTML 按钮。首先,我查看了 SVG 文档,找到了合适的 react 角度并将矩形替换为 <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>

这是我如何创建元素的片段
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> 的高度
  • button没有像按钮一样(鼠标悬停和鼠标按下没有反应)(这似乎已在 Chrome 和 Firefox 的新版本中修复)

  • JSFiddle here

    最佳答案

    我不知道你为什么说<body>元素未填充 <foreignObject> 的高度!?

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

    我添加了一个 SVG <rect><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>

    如您所见,它们的大小相同!

    enter image description here

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

    关于SVG 文档中的 HTML 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17471064/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com