I want to do keyboard shortcuts. For example, after clicking ctrl + b I got [b] [/ b]. I also want to have such a property that when I select the text with the mouse and click ctrl + b, I got [b] text [/ b]. My code currently looks like this:
html
<textarea id="textarea" rows="4" cols="50">
lorem lorem lorem lorem
</textarea>
JQuery
var textarea = $('#textarea');
textarea.mouseup(function (event) {
event.preventDefault();
var content = textarea.val(),
selectText = window.getSelection().toString(),
cursorPosition = textarea.prop('selectionStart'),
content = textarea.val(),
textBefore = content.substring(0, cursorPosition),
textAfter = content.substring(cursorPosition, content.length);
if(selectText.length > 0) {
textarea.keyup(function (event) {
if (event.ctrlKey && event.which == 66) {
textarea.val(content.replace(selectText, '[b]' + selectText + '[/b]'));
textarea[0].setSelectionRange(textBefore.length + selectText.length + 7, textBefore.length + selectText.length + 7);
} });
} else {
textarea.keyup(function (event) {
if (event.ctrlKey && event.which == 66) {
textarea.val(textBefore + '[b][/b]' + textAfter)
textarea[0].setSelectionRange(textBefore.length + 7, textBefore.length + 7);
}
});
}
});
The problem is that I can't separate it into events. Because sometimes I want to select text and sometimes I just want to add a tag. At this point, my code works so that I always have to click the mouse on the field and then add a marker. And I can't add a few markers side by side.
To sum up my task is that after clicking ctrl + b in the field will appear [b] [/ b]
, or after selecting the text and clicking ctrl + b will get [b] text [/ b]
Instead of textarea.mouseup, do textarea.keydown. That way you can put your mouse down and press ctrl + b. I also changed the code a bit, without using keypress inside the function and making it more efficient.
$('#textarea').keydown(function(e) { if (e.ctrlKey && e.key == 'b') { var length = $(this).val().length; var start = this.selectionStart; var end = this.selectionEnd; var selectedText = $(this).val().substring(start, end); var replacement = "[b]" + selectedText + "[/b]"; $(this).val($(this).val().substring(0, start) + replacement + $(this).val().substring(end, length)); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <textarea id="textarea" rows="4" cols="50">ducks</textarea>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.