首页 > 解决方案 > 在 textarea Reactjs 中键入时突出显示文本

问题描述

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

标签: reactjsfrontendtextarea

解决方案


它不是完整的解决方案,但您可以调整此示例:

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);
}

推荐阅读