嗨,所以我创建了这个代码很好.
document.getElementById("file").addEventListener('click',
function () {
var textArea = document.getElementById("newTextArea");
//Retrieve the selected text :
var selText = window.getSelection();
var text = textArea.innerHTML;
// I need to make a condition here. If the text doesn't have a span tag then do this:
if (document.querySelector('.test') === null) {
textArea.innerHTML = text.replace(selText, '<span class="test">'+selText+'</span>');
// if the text does have a span tag then remove the span tag
} else if (document.querySelector('.test') !== null) {
var deSelText = document.querySelector('.test');
var highlightedText = deSelText.innerHTML; …Run Code Online (Sandbox Code Playgroud)