Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当contentEditable div中存在选择时,如何触发事件?_Javascript - Fatal编程技术网

Javascript 当contentEditable div中存在选择时,如何触发事件?

Javascript 当contentEditable div中存在选择时,如何触发事件?,javascript,Javascript,当用户在contentEditable div中选择某个文本/元素时,我想触发一个事件。因此,我想禁用富文本编辑器中的某些按钮 有些事件可以根据内容的更改触发。仅当用户选择某些内容时,我才需要一个事件。您可以将事件侦听器添加到mouseup事件的元素中,然后从窗口获得选择: <div contenteditable="true" id="editableDiv">Some content</div> 相对简化的版本可能是这样的,根据您的需要,您可能需要处理像旧IE等

当用户在contentEditable div中选择某个文本/元素时,我想触发一个事件。因此,我想禁用富文本编辑器中的某些按钮


有些事件可以根据内容的更改触发。仅当用户选择某些内容时,我才需要一个事件。

您可以将事件侦听器添加到
mouseup
事件的元素中,然后从
窗口获得选择:

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

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

const handleSelection=function(){
const btn=document.querySelector('#btn');
让选择=window.getSelection().anchorNode.textContent
.子串(
window.getSelection().extendofset,
window.getSelection().AnchoroOffset
);
如果(selection.length!==0){
btn.setAttribute('disabled',true);
}否则{
btn.removeAttribute(“禁用”);
}
};
['mouseup','keyup','selectionchange'].forEach((e)=>{
document.querySelector(“#可编辑”).addEventListener(e,handleSelection);
});
#btn[禁用]{
游标:默认值;
不透明度:0.3;
}
按钮(选择某项内容时禁用)
我是一些可编辑的内容


您是否尝试过任何可以共享的代码?您可能可以将keyup事件绑定到元素并检查其中的选择。你应该给出一些代码,这样我们可以更好地帮助你。我没有尝试所有的可能性,但我得到了方向,这足以接受答案。谢谢
  document.getElementById("editableDiv").addEventListener("mouseup", function() {
    var s = window.getSelection();
    if(s == "something"){
       //do your thing
    }
  }, false);