开发者

SVG-based text input field

开发者 https://www.devze.com 2023-01-24 19:10 出处:网络
Has anyone seen any javascript implement开发者_如何转开发ation of a text input field besides http://www.carto.net/papers/svg/gui/textbox/ ?There is an interesting SVG node called foreignObject, which

Has anyone seen any javascript implement开发者_如何转开发ation of a text input field besides http://www.carto.net/papers/svg/gui/textbox/ ?


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消