这是一个工作示例,通过将 Sondre 给出的解决方案与 Mr_Green 的解决方案(将插入符号位置始终设置为以 contenteditable div 结尾)将插入符号放在末尾来完成。
http://jsfiddle.net/344m4/1/
var hashTagList = [];
function logHashList(){
hashTagList = [];
$('.highlight').each(function(){
hashTagList.push(this.innerHTML);
});
for(var i=0;i<hashTagList.length;i++){
alert(hashTagList[i]);
}
if(hashTagList.length==0){
alert('You have not typed any hashtags');
}
}
$(function() {
var hashtags = false;
$(document).on('keydown', '#example-one', function (e) {
arrow = {
hashtag: 51,
space: 32
};
var input_field = $(this);
switch (e.which) {
case arrow.hashtag:
e.preventDefault();
input_field.html(input_field.html() + "<span class='highlight'>#");
placeCaretAtEnd(this);
hashtags = true;
break;
case arrow.space:
if(hashtags) {
e.preventDefault();
input_field.html(input_field.html() + "</span> ");
placeCaretAtEnd(this);
hashtags = false;
}
break;
}
});
});
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}