簡體   English   中英

Javascript查找文本區域內[quote] [/ quote]之間的文本

[英]Javascript find and higlight text between [quote][/quote] within textarea

我有帶有預寫消息的HTML代碼。 我的目標是在我聚焦/單擊文本區域后,以黃色背景突出顯示[quote] [/ quote]之間的文本。

<textarea>
This is a test message.

[quote]Wise man said he is wise.[/quote] There could be more quotes too:

[quote]this is second quote [/quote]

He is correct.
</textarea>

可以使用純Javascript做到嗎? 我認為應該是這樣的:

textarea onfocus =“ function()”>

  • 在[quote] [/ quote]之間查找文本
  • 將黃色背景應用於找到的文本:background Color ='#ffc'

....

(如果沒有找到[quote] [/ quote],那么它應該什么也不做,即沒有警告)。

由於您無法使用<textatea>操作, <textatea>建議您看一下

<div contenteditable>

</div>

這是一個例子:

 var area = document.getElementById("area"); var text = area.innerHTML; area.innerHTML = text.replace(/\\[\\s*quote.*\\](.*)[^[]*\\[\\s*\\/quote.*\\]/ig, "<span>$1</span>"); 
 [contenteditable]{ white-space:pre-wrap; } [contenteditable] span{ background:#ffc; } 
 <div id="area" contenteditable> This is a test message. [quote]Wise man said he is wise.[/quote] There could be more quotes too: [quote]this is second quote [/quote] He is correct. </div> 

否則 ,由於您不能像對待實際HTML元素一樣將文textarea HTML元素視為突出顯示它們,所以→您應創建一個與文本區域大小相同(例如font-size等)的內存中元素,執行上述操作,計算位置生成的span元素,而不是在文本區域的各個位置上應用一些高光覆蓋,請注意如果窗口調整大小后它們會“跟進”……故事就這樣了……

這是一個實現上述功能的jQuery插件
http://mistic100.github.io/jquery-highlighttextarea/

當前,我正在研究兩種方法: 高亮顯示Textarea內的文本 ,該文本描述了此插件的完成方式: https : //github.com/lonekorean/highlight-within-textarea

MediaWiki的語法higlighter: 來源方法說明

它們都在文本區域后面使用具有相同字體和位置的附加元素來顯示背景顏色。 使Textarea背景透明。 然后在編輯和滾動時同步內容,並在textarea和后面的元素之間滾動。

這是我的簡化代碼: https : //codepen.io/bunyk-1472854887/full/RLJbNq/

熒光筆的核心邏輯如下(略過一些細節):

textarea.addEventListener('keyup', textUpdate);
textarea.addEventListener('scroll', scrollUpdate);

function textUpdate() {
    var html = html_escape(textarea.value);
    enter code here
    html = html.replace(/\[quote\](.*?)\[\/quote\]/g, '[quote]<span class="quote">$1</span>[/quote]');

    background.innerHTML = html;
}

function scrollUpdate() {
    background.scrollTop = textarea.scrollTop;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM