我正在使用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
但是当我将其更改为ul
和li
时,它无效。
<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());
});
编辑: - 在Mozila工作但不在IE工作
答案 0 :(得分:0)
使用非表单元素时,只需将.val()
更改为.text()
:
$("#myIframe").contents().find("body").insertAtCaret( $(this).text() );