简体   繁体   English

更改部分文字的颜色 <p> 根据用户选择标记?

[英]Change color of a part of text inside a <p> tag according to user selection?

I'm developing an extension for Google Chrome; 我正在为Google Chrome开发扩展程序; as a part of it there is a text highlighting capability. 作为其一部分,具有文本突出显示功能。

I've managed to highlight a complete <p></p> tag (or any other tag) but I can't figure out how to highlight a part inside a tag. 我设法突出显示了完整的<p></p>标签(或任何其他标签),但是我不知道如何突出显示标签中的零件。 (user will not select an entire tag) (用户不会选择整个标签)

I found that I should use <span> inside the <p> tag but I can't figure out a way to do it. 我发现应该在<p>标记内使用<span> ,但是我找不到解决方法。

  1. How do I identify the part that the user selected? 如何识别用户选择的零件?

  2. How do I highlight the selected part (eg change the back color)? 如何突出显示选定的部分(例如更改底色)?

A detailed explanation would be really helpful and highly appreciated, since I'm new to extension development. 因为我是扩展开发的新手,所以详细的解释将非常有帮助并受到高度赞赏。

What I've done in the past is split the text into 3 parts: 我过去所做的就是将文本分为3部分:

1- the text before the selected text. 1-所选文本之前的文本。

2- the selected text. 2-选定的文本。

3- the text after the selected text. 3-所选文本后的文本。

Then I clear the element's innerHTML (or another method), add the 'before' text, add a span with their text as its text (which has a style that can be highlighted), and the 'after' text. 然后,我清除元素的innerHTML(或其他方法),添加“ before”文本,添加带有其文本作为其文本(具有可突出显示的样式)的span以及“ after”文本。


To find out what they selected, you can use ranges (selectionStart & selectionEnd) eg, 要找出他们选择的内容,您可以使用范围(selectionStart和selectionEnd),例如,

var html = elem.innerHTML;
var before = html.slice(0, elem.selectionStart);
var selected = html.slice(elem.selectionStart, html.selectionEnd);
var after = html.substring(html.selectionEnd);

This method isn't perfect, but it's a good starter to learn with. 这种方法并不完美,但它是一个很好的入门者。

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

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