【问题标题】:Highlight text as you type in textarea Reactjs在 textarea Reactjs 中键入时突出显示文本
【发布时间】:2021-12-20 10:25:15
【问题描述】:

我需要在 FrontEnd 中执行一个行为,但我不知道该怎么做:在文本区域内,我必须在用户键入时为某些关键字(如“+project”、“@context”)添加背景,就好像它是类似于 Regex 测试工具的标记文本。

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: reactjs frontend textarea


【解决方案1】:

这不是完整的解决方案,但您可以修改此示例:

https://jsfiddle.net/julmot/hdyLpy37/

它使用 markjs 库:

https://markjs.io/

这里是javascript代码:

// Create an instance of mark.js and pass an argument containing
// the DOM object of the context (where to search for matches)
var markInstance = new Mark(document.querySelector(".context"));
// Cache DOM elements
var keywordInput = document.querySelector("input[name='keyword']");
var optionInputs = document.querySelectorAll("input[name='opt[]']");

function performMark() {

  // Read the keyword
  var keyword = keywordInput.value;

  // Determine selected options
  var options = {};
  [].forEach.call(optionInputs, function(opt) {
    options[opt.value] = opt.checked;
  });

  // Remove previous marked elements and mark
  // the new keyword inside the context
  markInstance.unmark({
    done: function(){
        markInstance.mark(keyword, options);
    }
  });
};

// Listen to input and option changes
keywordInput.addEventListener("input", performMark);
for (var i = 0; i < optionInputs.length; i++) {
  optionInputs[i].addEventListener("change", performMark);
}

【讨论】:

    猜你喜欢
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    相关资源
    最近更新 更多