简体   繁体   English

如何使用选择范围更改文本区域中选定文本的突出显示颜色?

[英]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.我目前正在使用 Web API 中的选择范围突出显示文本区域中的文本。这工作正常,但是,我想更改默认突出显示颜色和不透明度。 I have attempted to change this with css (see example below), however, it does not update the color of the selection.我试图用 css 来改变它(见下面的例子),但是,它不会更新选择的颜色。 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 https://codepen.io/jyh7a/pen/xxpLMZZ

HTML 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 CSS

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

JS 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我搜索了 setSelectionRange
I made the above example by looking at the MDN official documentation.上面的例子是我看MDN官方文档做的。
(Link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange ) (链接: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

Hope the above code was helpful to you.希望以上代码对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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