Ajax工具包文本编辑器子控件

时间:2014-04-29 12:35:24

标签: javascript jquery html css

我正在使用Microsoft ajax-toolkit提供的文本编辑器 它在浏览器上呈现iframe。我在该编辑器中添加了一个下拉列表,我希望当用户更改下拉索引时,应在编辑器当前光标位置添加该值。

<iframe id="myIframe"></iframe>
  <select id="myOptions">
   <option value="myValue1">My Value 1</option>
   <option value="myValue2">My Value 2</option>
   <option value="myValue3">My Value 3</option>
   <option value="myValue4">My Value 4</option>
   <option value="myValue5">My Value 5</option>
</select>

和javascript

$.fn.extend({
insertAtCaret: function (myValue) {
    var doc = this[0].ownerDocument;
    var win = doc.defaultView || doc.parentWindow;
    if (win.getSelection) {
        var selObj = win.getSelection();            
        var myRange  = selObj.getRangeAt(0);
        selObj.deleteFromDocument();
        myRange.insertNode(doc.createTextNode(myValue));
        selObj.addRange(myRange);
        selObj.collapseToEnd();
        this.focus();
    }
    else if (doc.selection) {
        this.focus();
        sel = doc.selection.createRange();
        sel.text = myValue;
        this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.innerHTML = this.innerHTML.substring(0, startPos) + myValue + this.innerHTML.substring(endPos, this.innerHTML.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;
     }
   }
});

$("#myIframe").contents().find("body").attr("contenteditable", "true");
$("#myOptions").on("change", function() {
    $("#myIframe").contents().find("body").insertAtCaret($(this).val());
});

工作正常fiddle

但是当我将其更改为ulli时,它无效。

<iframe id="myIframe"></iframe>
<ul id="myOptions">
    <li value="myValue1">My Value 1</li>
    <li value="myValue2">My Value 2</li>
    <li value="myValue3">My Value 3</li>
    <li value="myValue4">My Value 4</li>
    <li value="myValue5">My Value 5</li>
</ul>

脚本

$("#myIframe").contents().find("body").attr("contenteditable", "true");
$("#myOptions").on("change", function() {
    $("#myIframe").contents().find("body").insertAtCaret($(this).val());
});

Fiddle

编辑: - 在Mozila工作但不在IE工作

1 个答案:

答案 0 :(得分:0)

使用非表单元素时,只需将.val()更改为.text()

$("#myIframe").contents().find("body").insertAtCaret( $(this).text() );

http://jsfiddle.net/mblase75/5Pc55/46/