【发布时间】:2014-05-12 16:43:25
【问题描述】:
我尝试在 javascript 中创建一段代码,以在插入符号所在的可内容编辑“div”中添加一个节点(“span”、“strong”...)(当我单击“按钮”时)。
我开始思考这样的代码(它不起作用,这只是一个开始):http://jsfiddle.net/Md8KX/2/
HTML:
<div id="myDiv" contenteditable="true">
<strong>Test:</strong> This is a <strong>really</strong> good test.
</div>
<button type="button" id="myButton">Add a span</button>
CSS:
#myDiv{padding:15px;border:solid 1px #000;}
JS:
// Variable to stock the caret position
var caretPosition = 0;
// Event to get caret position on keyup and on blur
$('#myDiv').on('keyup focus', function () {
caretPosition = getCaretPosition(this);
});
// Event to add node when click on button
$('#myButton').on('click', function (e) {
e.preventDefault();
addNode(this, caretPosition, '<span>Node</span>');
});
// Function to get caret position with 1 param : the editable box
var getCaretPosition = function (editableBox) {
var position = 0;
// TO DO : get caret position
return position;
}
// Function to add node with 3 params : the editable box, the caret position and the node to add
var addNode = function (editableBox, caretPosition, nodeToAdd) {
// TO DO : add node in element
}
但是我完全不知道获取光标位置然后在此时插入一个节点:) 我在 javascript 或“createTextRange”中阅读了有关“范围”属性的内容,但我不确定我是否理解,我不知道这是否是最好的方法。
您有什么想法或可以帮助我开始的曲目吗? 提前谢谢!
【问题讨论】:
-
@TimDown :效果很好,谢谢!但是还有一个问题:如果同时另一个 DOM 元素获得焦点(或者如果 contenteditable 失去焦点),该节点将不会被添加到插入符位置,而是在 div 的开头。您是否有保存插入符号位置并将其保存在变量中以避免此问题的想法?
-
在失去焦点之前保存范围。示例:stackoverflow.com/questions/4687808/…
标签: javascript jquery contenteditable