SVG-based text input field

前端 未结 4 2130
孤街浪徒
孤街浪徒 2020-12-13 18:44

Has anyone seen any javascript implementation of a text input field besides http://www.carto.net/papers/svg/gui/textbox/ ?

相关标签:
4条回答
  • 2020-12-13 19:13

    I've been looking for this for a project I'm working on. We couldn't find anything suitable so we're coding our own solution, I hope it's good enough so that someone else does not have to do the same: http://engelfrost.github.io/svg-input-elements/

    0 讨论(0)
  • 2020-12-13 19:18

    There is an interesting SVG node called foreignObject, which allows you to place HTML, flash, etc within your SVG code. Try the following:

    <svg width="100%" height="500" xmlns="http://www.w3.org/2000/svg>
      <foreignObject x="10" y="10" width="100" height="150">
          <div xmlns="http://www.w3.org/1999/xhtml">
          <input></input>
              </div>
      </foreignObject>
    </svg>
    

    EDIT: added xmlns so it works for IE.

    0 讨论(0)
  • 2020-12-13 19:35

    I've seen another one, note that it requires support for the 'editable' attribute from SVG Tiny 1.2... it's definately more native in the sense that there's not a single line of javascript in that example. Try it out in Opera.

    0 讨论(0)
  • 2020-12-13 19:37

    This is for MS Internet Explorer, not tested in any other browser.

    As mentioned in another comment, up to IE11 does not support foreignObject. Instead, use the contentEditable attribute.

    Plain SVG example

    <svg width="100" height="100" >
        <g transform="translate(40,40)">
            <text contentEditable="true">foo</text>
        </g>
    </svg>
    

    D3.js example with data binding

    Here we listen for key events to write the text back to the data.

    selection.
      .append("text")
        .attr("contentEditable", true)
        .text(function(d) { return d.text })
        .on("keyup", function(d) { d.text = d3.select(this).text(); });
    

    Note: If nodes are dynamically generated like with d3.js, you must capitalize contentEditablelike such (this took me some time)!

    Note: Do not style your text with pointer-events: None, for then you cannot interact with the text anymore, regardless of the contentEditable setting.

    0 讨论(0)
提交回复
热议问题