用光标指针在jWYSIWYG中注入某些东西?

时间:2011-07-20 18:09:05

标签: jquery jwysiwyg

我想在光标指针的jWYSIWYG中注入下拉列表选中的值。我想这样做:

<select id="shirt" name="shirt">
      <option value="small">Small</option>
      <option value="medium">Medium</option>
      <option value="large">Large</option>
</select>
<a href="#" id="btn_insert" name="btn_insert">Insert</a>
<textarea id="testing_txt" name="testing_txt"></textarea>

1 个答案:

答案 0 :(得分:0)

技巧是可靠地获得光标位置。我发现如何从现有的SO thread执行此操作。一旦你有光标位置,只需要获取前后文本,然后在中间插入新值。

http://jsfiddle.net/Vr99u/1/

$("#mybutton").click( function() {
var pos = getCaret(document.getElementById('mytextarea'));
var currentText = $("#mytextarea").val();
var currentTextStart = currentText.substr(0, pos);
var currentTextEnd = currentText.substr(pos, currentText.length);
var newText = currentTextStart + $("#myselect").val() + currentTextEnd;
$("#mytextarea").val(newText); });


function getCaret(node) {
  if (node.selectionStart) {
    return node.selectionStart;
  } else if (!document.selection) {
    return 0;
  }

  var c = "\001",
      sel = document.selection.createRange(),
      dul = sel.duplicate(),
      len = 0;

  dul.moveToElementText(node);
  sel.text = c;
  len = dul.text.indexOf(c);
  sel.moveStart('character',-1);
  sel.text = "";
  return len;
}