Javascript 使用chrome扩展为ContentItable中的文本加下划线

Javascript 使用chrome扩展为ContentItable中的文本加下划线,javascript,jquery,google-chrome-extension,Javascript,Jquery,Google Chrome Extension,我正在尝试做一个chrome扩展,在特定的单词下面加下划线。 假设用户写“hello”,那么我想在它下面加下划线。 在Facebook和其他社交媒体中,文本字段是一个内容可编辑的div 如何访问该文本并仅操纵其中的特定单词? 我试过这样做,但没有成功 $('body').on('focus', '[contenteditable]', function() { const $this = $(this); $this.data('before', $this.html()); }

我正在尝试做一个chrome扩展,在特定的单词下面加下划线。 假设用户写“hello”,那么我想在它下面加下划线。 在Facebook和其他社交媒体中,文本字段是一个内容可编辑的div

如何访问该文本并仅操纵其中的特定单词? 我试过这样做,但没有成功

$('body').on('focus', '[contenteditable]', function() {
    const $this = $(this);
    $this.data('before', $this.html());
}).on('blur keyup paste input', '[contenteditable]', function() {
    const $this = $(this);
    if ($this.data('before') !== $this.html()) {
        $this.data('before', $this.html());
        $this.trigger('change');

    if ($this.text().includes("hello")){

        //document.execCommand('undeline'); //didn't work 
        //$this.style.textDecorationColor="red"; // neither did this
        //$this.style.textDecorationStyle="wavy";
    }
    }
});
注意:我尝试了
document.execCommand
,但没有给出任何结果

我的纯JS解决方案:

    function logSelection(event) {
      const selection = window.getSelection().toString();
      const log = document.getElementById('log');
      console.log(selection, event); // debug

      // colors must be in hexadicemal (no #)
      const color = 'ff0000';
      const backColor = '0000ff';

      // apply css if you want
      this.style.textDecorationStyle="wavy";
      this.style.textDecorationColor='#'+color;

      document.execCommand('underline');
      document.execCommand('BackColor', false, '#' + backColor);
      document.execCommand('foreColor', false, color);
      //document.execCommand('HiliteColor', false, '#' + color); not working

      log.textContent = `You selected: ${selection}`;
    }

    const content = document.querySelector('div[contenteditable]');
    content.addEventListener('click', logSelection);
您还可以查看文档

检查它是否有助于您进行样式设置