【问题标题】:underline text in contetnteditable using chrome extension使用 chrome 扩展在 contetnteditable 中下划线文本
【发布时间】:2019-12-31 19:43:14
【问题描述】:

我正在尝试做一个强调特定单词的 chrome 扩展。 假设用户写“你好”,那么我想给它加下划线。 在 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,但没有给出任何结果

【问题讨论】:

标签: javascript jquery google-chrome-extension


【解决方案1】:

我的纯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);

您也可以查看document.execCommand 文档

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多