JSFiddle - React, Tailwind, and code Playground
by itlogunov
HTML
<button class="input">Вставить радио кнопки</button>
<div class="edit" contenteditable>
<p>
нажмите пробел после текста или с новой строки пробел и нажмите вставить радио кнопки, появятся символы, если пробел не ставить все отлично вставляется. как от них избавиться?
</p>
</div>
CSS
.edit {
border: 1px solid #000;
}
JavaScript
function insertAtCaret(obj, caret, html){
if (document.selection) {
obj.focus();
sel = document.selection.createRange();
sel.text = html;
obj.focus();
} else if (window.getSelection) {
txt = obj.innerHTML;
if (caret == -1) {
txt = txt.substring(caret) + html;
} else {
txt = txt.substring(0, caret) + html + txt.substring(caret);
}
obj.innerHTML = txt;
obj.focus();
} else {
obj.innerhtml += html;
obj.focus();
};
};
$('.edit').click(function(e){
insertCurrentPlace = ''; // ловим текущий тег
caret = ''; // положение каретки
insertCurrentPlace = e.target;
caret = window.getSelection().anchorOffset;
});
$(document).on('keyup', '.edit', function(e){
insertCurrentPlace = ''; // ловим текущий тег
caret = ''; // положение каретки
caret = window.getSelection().anchorOffset;
if (window.getSelection().anchorNode.nodeName == '#text') {
insertCurrentPlace = window.getSelection().anchorNode.parentNode;
} else {
insertCurrentPlace = window.getSelection().anchorNode;
}
});
$('.input').click(function(){
var html = '<input type="radio" name="radio" value="да"/>Да<input type="radio" name="radio" value="нет"/>Нет';
insertAtCaret(insertCurrentPlace, caret, html);
});