如何更改textarea选定文本的颜色?

use*_*672 2 html javascript css jquery textarea

我有textarea并且我想更改所选文本的颜色。例子:

var text = "abcdefg";
Run Code Online (Sandbox Code Playgroud)

我想更改所选文本的颜色efg

这是我的代码:

var input = document.getElementById('area');
var value = input.value.substr(input.selectionStart, input.selectionEnd - input.selectionStart);
$('#abc').find(value).attr('color',color);
Run Code Online (Sandbox Code Playgroud)

Moh*_*mad 5

使用::selection选择部分文本的 CSS 选择器。您可以将 CSS 属性添加到元素的选定文本中。

var textarea = document.querySelector("textarea");
textarea.selectionStart = 12;
textarea.selectionEnd = 23;
Run Code Online (Sandbox Code Playgroud)
::-moz-selection { 
    color: red;
}
::selection {
    color: red;  
}
Run Code Online (Sandbox Code Playgroud)
<textarea>My textarea highlighted text</textarea>
Run Code Online (Sandbox Code Playgroud)