2016-11-15 37 views
1

我有文本框/ textarea输入字段,通过选择内部的一些文本如何将字符添加到JavaScript中的文本框/ textarea中的选定文本按键

上选择“的Mes”并按下CTRL + B应该追加<b>(或任何字符或我所选择的多个字符)到所选的文本子文本和最后一个消息

测试消息在以JavaScript两端如下所示

测试<b>Mes<b>鼠尾草与子文本和最后一个消息

我能够模拟Ctrl + B关键事件成功但无法用新文本替换选定的文本,请帮助。

回答

1

你可以选择开始和在textarea的相应字段结束。

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
 
<textarea>Test Message with sub text and last message</textarea> 
 
<script> 
 
jQuery('textarea').on('keydown', function(e) { 
 
\t if (e.keyCode == 66 && (e.metaKey || e.ctrlKey)) { 
 
\t \t e.preventDefault(); 
 

 
\t \t var text = jQuery(this).val(); 
 
\t \t var start = this.selectionStart; 
 
\t \t var end = this.selectionEnd; 
 
\t \t var selection = '<b>' + text.substring(start, end) + '</b>'; 
 
\t \t text = text.substring(0, start) + selection + text.substring(end); 
 
\t \t jQuery(this).val(text); 
 
\t \t this.selectionStart = start; 
 
\t \t this.selectionEnd = start + selection.length; 
 
\t } 
 
}); 
 
</script>

+0

非常感谢你的快速反应 – Kiran

1

以下函数将选定的文本包装在具有给定字符串的文本区域中。

我写的情况为例

function wrapSelection(textArea, wrappingString) { 
    var s = textArea.selectionStart; 
    var e = textArea.selectionEnd; 
    var oldValue = textArea.value; 
    var newValue = oldValue.slice(0, s) + wrappingString + oldValue.slice(s, e) + wrappingString + oldValue.slice(e, oldValue.length); 
    textArea.value = newValue; 
} 

var element = document.getElementById('your-input-element'); 
element.onselect = function() { 
    wrapSelection(element, '<b>'); 
} 
+0

非常感谢你的快速反应 – Kiran