[英]How to trigger an event when there is selection inside a contentEditable div?
当用户在contentEditable div中选择一些文本/元素时,我想触发一个事件。 因此,我想停用RTF编辑器中的某些按钮。
根据内容的更改可以触发一些事件。 当用户选择一些内容时,我只想要一个事件。
您可以将事件侦听器添加到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);
一个相对简化的版本可能看起来像这样,根据您的需要,您可能需要处理不支持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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.