当内容中有选择时如何触发事件可编辑 div



我想在用户选择内容可编辑div中的某些文本/元素时触发事件。 因此,我想停用富文本编辑器中的某些按钮。

有些

事件可以根据内容的变化触发。我只想要当用户选择某些内容时的事件。

一个相对简化的版本可能看起来像这样,根据您的需要,您可能需要处理不支持window.getSelection()的旧IE等浏览器!

const handleSelection = function() {
  const btn = document.querySelector('#btn');
  let selection = window.getSelection().anchorNode.textContent
    .substring(
      window.getSelection().extentOffset, 
      window.getSelection().anchorOffset
    );
  if (selection.length !== 0) {
    btn.setAttribute('disabled', true);
  } else {
    btn.removeAttribute('disabled');
  }
};
['mouseup', 'keyup', 'selectionchange'].forEach((e) => {
  document.querySelector('#editable').addEventListener(e, handleSelection);
});
#btn[disabled] {
  cursor: default;
  opacity: 0.3;
}
<button type="button" id="btn">Button (disabled when something is selected)</button>
<div id="editable" contenteditable>
  <p>I'm some content that is editable!</p>
</div>

您可以将

事件侦听器添加到mouseup事件的元素中,并从window之后获取选择:

<div contenteditable="true" id="editableDiv">Some content</div>

和 js:

  document.getElementById("editableDiv").addEventListener("mouseup", function() {
    var s = window.getSelection();
    if(s == "something"){
       //do your thing
    }
  }, false);

最新更新