введите выделение для жирного и курсива вокруг выделения - PullRequest
0 голосов
/ 07 июня 2018

Итак, мне нужно добавить сочетания клавиш для уценки жирным шрифтом / курсивом.Я провел некоторое исследование и попытался сделать свое собственное, но я не могу сделать его идеальным.это должно быть сделано так, чтобы .. пожилые люди .. могли его использовать, и результаты будут достаточно хороши для просмотра молодыми людьми.

Вставьте текстдо и после выбора в текстовой области с помощью javascript

Я посмотрел и провел исследование, и это самое близкое, что я могу найти.тем не менее, первый полностью ошибочен, так как удаляет весь текст до и после выделения, и мне не нужно находить / заменять.

второй вариант был бы идеальным, но я не могузаставить его работать.Я получаю ошибки, такие как cannot read property 'createrange' of undefined.

код, который я сделал:

text = inputBox.value;
selected = text.slice(inputBox.selectionStart,inputBox.selectionEnd);
if(selected != ""){
text = text.replace(selected,"**"+selected+"**");
inputBox.value=text;

однако, он имеет огромный недостаток: , если есть несколько случаевиз того же текста, он делает первый, а не выделенный, курсивом / жирным шрифтом / подчеркнутым

Ответы [ 2 ]

0 голосов
/ 25 января 2019

Это просто расширенная версия функции, заданной @ CcJokerPol.

Дополнительные функции:

  • Это добавляет text, а также удаляет тоже.
  • позволяет также добавлять текст по умолчанию.
  • Фрагмент показывает, что для вызова функции используются также ctrl+b, ctrl+i, ctrl+u.
  • Можно также добавить несколько уценок, например: **++underlined bold text++**

Пример:

  • текст для bold => aтекст **bold**
  • текст для удаления **bold** => текст для удаления bold
  • текст для удаления **bold** => текст для удаленияbold

Звонок тот же insertFormating(inputBox, "**", "bold");

$(document).keydown(function(e) {
	if (e.ctrlKey && $.inArray(e.keyCode, [66, 73, 85, 76]) > -1) {
		var keyCode = e.keyCode;
		var focused = document.activeElement;
		var id = focused.id;
    e.preventDefault();
    if (keyCode == 66) {
      insertFormating(focused, "**", "bold");
    } else if (keyCode == 73) {
      insertFormating(focused, "__", "italic");
    } else if (keyCode == 85) {
      insertFormating(focused, "++", "underline");
    } else if (keyCode == 76) {
      insertFormating(focused, "[", "link title", "](http://www.example.com)");
    }
	}
});

function insertFormating(txtarea, text, defaultTxt = "", text2 = "") {
	var selectStart = txtarea.selectionStart
	var selectEnd = txtarea.selectionEnd
	var scrollPos = txtarea.scrollTop;
	var caretPos = txtarea.selectionStart;
	var mode = 0; //Adding markdown with selected text
	var front = (txtarea.value).substring(0, caretPos);
	var back = (txtarea.value).substring(selectEnd, txtarea.value.length);
	var middle = (txtarea.value).substring(caretPos, selectEnd);

	if (text2 == "") {
		text2 = text;
	}
	var textLen = text.length;
	var text2Len = text2.length;

	if (selectStart === selectEnd) {
		middle = defaultTxt;
		mode = 1; //Adding markdown with default text
	} else {
		if (front.substr(-textLen) == text && back.substr(0, text2Len) == text2) {
			front = front.substring(0, front.length - textLen);
			back = back.substring(text2Len, back.length);
			text = "";
			text2 = "";
			mode = 2; //Removing markdown with selected text eg. **<selected>bold<selected>**
		} else if (middle.substr(0, textLen) == text && middle.substr(-text2Len) == text2) {
			middle = middle.substring(textLen, middle.length - text2Len);
			text = "";
			text2 = "";
			mode = 3; //Removing markdown with selected text eg. <selected>**bold**<selected>
		}
	}
	txtarea.value = front + text + middle + text2 + back;
	if (selectStart !== selectEnd) {
		if (mode === 0) {
			txtarea.selectionStart = selectStart + textLen;
			txtarea.selectionEnd = selectEnd + textLen;
		} else if (mode === 2) {
			txtarea.selectionStart = selectStart - textLen;
			txtarea.selectionEnd = selectEnd - textLen;
		} else if (mode === 3) {
			txtarea.selectionStart = selectStart;
			txtarea.selectionEnd = selectEnd - textLen - text2Len;
		}
	} else {
		txtarea.selectionStart = selectStart + textLen;
		txtarea.selectionEnd = txtarea.selectionStart + middle.length;
	}
	txtarea.focus();
	txtarea.scrollTop = scrollPos;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="5" cols="60">A quick brown fox jumps over the lazy dog.
Test it here.</textarea>

Команды быстрого вызова, используемые во фрагменте:

  • ctrl+b => Жирный =>**bold text**
  • ctrl+i => Курсив => __italic text__
  • ctrl+u => Подчеркнуть => ++underlined text++
  • ctrl+l => Ссылка => [link title](http://www.example.com)

Обновление:

  • Теперь вы можете добавлять различные начальные и закрывающие теги уценки
  • например. insertFormating(focused, "[", "link title","](http://www.example.com)");
0 голосов
/ 11 ноября 2018

эта функция использует selectionStart и selectionEnd вместе с подстрокой для вставки текста до и после выделенного текста.

async function insertFormating(txtarea, text) {
    var selectStart = txtarea.selectionStart
    var selectEnd = txtarea.selectionEnd
    var scrollPos = txtarea.scrollTop;
    var caretPos = txtarea.selectionStart;

    var front = (txtarea.value).substring(0, caretPos);
    var back = (txtarea.value).substring(txtarea.selectionEnd, txtarea.value.length);
    var middle = (txtarea.value).substring(caretPos, txtarea.selectionEnd);
    txtarea.value = front + text + middle + text + back;
    if (selectStart !== selectEnd) {
        txtarea.selectionStart = selectStart + text.length
        txtarea.selectionEnd = selectEnd + text.length
    } else {
        txtarea.selectionStart = selectStart + text.length
        txtarea.selectionEnd = txtarea.selectionStart
    }
    txtarea.focus();
    txtarea.scrollTop = scrollPos;
}

теперь вы можете вызывать insertFormating(inputBox, '**'); для вставки жирным шрифтом или insertFormating(inputBox, '_');для курсива.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...