首页 > 解决方案 > JointJS:无法使用 JSON 以自定义形状显示 foreignObject

问题描述

我正在尝试在 JointJS 中定义一个包含标签的自定义形状。如果我将标记定义为字符串,它就可以正常工作:

joint.shapes.examples.CustomRectangle = joint.shapes.standard.Rectangle.define('examples.CustomRectangle', {
  markup: '<rect class="card"/><foreignObject x="10" y="10" height="60" width="100"><input xmlns="http://www.w3.org/1999/xhtml" type="text"></input></foreignObject>',

  attrs: {
    rect: {
      refWidth: '100%',
      refHeight: '100%',
      strokeWidth: 5,
      stroke: '#000000',
      fill: 'white'
    },
  }
});

请参阅此代码笔并注意输入框在正方形内可见:http: //jsfiddle.net/dovrosenberg/kbmwfg1a/89/

如果我在 SVG 中定义了看起来相同但使用 JSON 的 XML:

joint.shapes.examples.CustomRectangle = joint.shapes.standard.Rectangle.define('examples.CustomRectangle', {
  markup: [{
      tagName: 'rect',
      selector: 'rect'
    },
    {
      tagName: 'foreignObject',
      selector: 'fo',
      attributes: {
        x: '10',
        y: '10',
        width: '60',
        height: '100',
      },
      children: [{
        tagName: 'input',
        selector: 'inpt',
        attributes: {
          xmlns: 'http://www.w3.org/1999/xhtml',
          type: 'text',
        },
      }]
    }
  ],
  attrs: {
    rect: {
      refWidth: '100%',
      refHeight: '100%',
      strokeWidth: 5,
      stroke: '#000000',
      fill: 'white'
    },
  }
});

请参阅此代码笔并注意输入框不可见:http: //jsfiddle.net/dovrosenberg/asnvwe1r/4/

当我在浏览器中查看它时,生成的 SVG 看起来几乎相同。我能看到的唯一区别是 JSON 版本插入joint-selector属性,但我认为这无关紧要。

更奇怪的是,如果您在调试器中编辑 HTML 并对 foreignObject 标记进行微小更改(例如更改关节选择器属性之一),则输入变为可见。

这不应该工作吗?

标签: javascripthtmlsvgjointjsforeignobject

解决方案


感谢罗伯特朗森的精彩评论,我能够弄清楚。正确的标记如下(或参见http://jsfiddle.net/dovrosenberg/asnvwe1r/8/)。不同之处在于新namespaceURI密钥。

joint.shapes.examples.CustomRectangle = joint.shapes.standard.Rectangle.define('examples.CustomRectangle', {
  markup: [{
      tagName: 'rect',
      selector: 'rect'
    },
    {
      tagName: 'foreignObject',
      selector: 'fo',
      attributes: {
        x: '10',
        y: '10',
        width: '60',
        height: '100',
      },
      children: [{
        tagName: 'input',
        selector: 'inpt',
        namespaceURI: 'http://www.w3.org/1999/xhtml',
        attributes: {
          type: 'text',
        },
      }]
    }
  ],
  attrs: {
    rect: {
      refWidth: '100%',
      refHeight: '100%',
      strokeWidth: 5,
      stroke: '#000000',
      fill: 'white'
    },
  }
});

推荐阅读