Как стилизовать отдельные слова в поле ввода textarea?
Допустим пользователь вводит текст в textarea - "I have no" и как только он вводит "I have no #money" тег должен быть выделен каким-то стилем, а весь остальной текст остаться классическим. Вот регулярное выражение которым можно распознать тег:
/#[a-zA-Z0-9А-Яа-я]+\b/g
Возможно ли реализовать такую функцию и если да, то как?
Ответы (2 шт):
Автор решения: UserTest013
→ Ссылка
В textarea никак нельзя, но легко можно сделать собственное решение. Вот так например:
const highlighted = /#[a-zA-Z0-9А-Яа-я]+/g;
editor.addEventListener('input', function(event) {
view.innerHTML = this.innerHTML.replace(highlighted, function(text) {
return '<span class="highlighted">' + text + '</span>';
});
});
editor.addEventListener('scroll', function() {
view.scrollTop = this.scrollTop;
view.scrollLeft = this.scrollLeft;
});
#editor,
#view {
position: absolute;
width: 80%;
margin: 0 auto;
padding: 1em;
height: 100px;
border: 1px solid black;
overflow: auto;
}
#editor {
z-index: 10;
background: transparent;
color: transparent;
caret-color: black;
}
#view {
color: black;
}
span.highlighted {
color: red;
}
<div id="editor" contenteditable="true"></div>
<div id="view" class="original"></div>
Автор решения: Проста Miha
→ Ссылка
const text = document.querySelector('textarea');
const pre = document.querySelector('pre');
text.addEventListener('input', function(e) {
let string = this.value;
let array = string.split(/(\s+)/);
for (let i = 0; i < array.length; i++) {
if (array[i].includes('#')) {
array[i] = "<span class='highlight'>" + array[i] + "</span>";
}
}
string = array.join('');
pre.innerHTML = string;
});
.textarea {
position: relative;
height: 200px;
background-color: #000;
}
.textarea textarea {
resize: none;
z-index: 1;
caret-color: white;
color: transparent;
background-color: transparent;
}
.textarea textarea,
.textarea pre {
position: absolute;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-family: consolas;
font-size: 15px;
line-height: 1.2em;
border: 0;
white-space: pre-wrap;
}
.textarea pre {
top: 0;
left: 0;
z-index: 0;
color: #fff;
white-space: -moz-pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
}
.highlight{
background-color: red;
}
<div class="textarea">
<textarea rows='5' cols='50'></textarea>
<pre></pre>
</div>