简体   繁体   中英

How to change the highlight color of selected text in a textarea, using selection range?

I am currently highlighting text in a textarea using a selection range from the Web API. This works fine, however, I would like to change the default highlight color and opacity. I have attempted to change this with css (see example below), however, it does not update the color of the selection. Does anyone know of a way to achieve this?

// select text
const startPosition = 0;
const endPosition = 25;
textarea.setSelectionRange(startPosition, endPosition);

// CSS
textarea::selection {
    background-color: red;
}

I don't understand exactly what you want.
Did you want an answer like the code below?
https://codepen.io/jyh7a/pen/xxpLMZZ

HTML

<input type="text" id="text-box" size="20" value="Mozilla">
<button onclick="selectText()">Select text</button>

<hr/>

<textarea rows="6" cols="40">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</textarea>

<hr/>

<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</p>

CSS

::selection {
    background-color: rgba(255,0,0,0.2);
}

JS

function selectText() {
  
  const input = document.getElementById('text-box');  
  input.focus();
  input.setSelectionRange(2, 5);

  setTimeout(() => {
    const textarea = document.querySelector('textarea');
    textarea.focus();
    textarea.setSelectionRange(0, 20);
  }, 1000)
  
     
  // // ERROR! 
  // // setSelectionRange function only use HTMLInputElements
  // const p = document.querySelector('p');
  // p.setSelectionRange(0, 20);
}

I searched for setSelectionRange
I made the above example by looking at the MDN official documentation.
(Link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange )

Hope the above code was helpful to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM