[英]How can I prevent removing the selection from text after a click?
I'm working on an admin-panel where the inputs are contenteditable divs. 我正在管理输入内容可编辑的div的管理面板。 I also have a toolbar (containing some formatting buttons), that shows up if you have any selected text inside the div, and will be removed if not.
我还有一个工具栏(包含一些格式按钮),如果您在div中有任何选定的文本,则会显示该工具栏,否则将被删除。
The problem is, that when I click to any button in the toolbar, the selection from the document will be removed, so I can't insert for example a tag before and after the text. 问题是,当我单击工具栏上的任何按钮时,文档中的选择将被删除,因此我无法在文本前后插入例如标签。
Can I prevent this behaviour, or is there any workaround for this? 我可以防止这种行为吗,或者有任何解决方法?
It's not inevitable that the selection is lost when the user clicks a button. 当用户单击按钮时,选择丢失是不可避免的。 The two ways I know to avoid it are:
我知道避免这种情况的两种方法是:
mousedown
rather than the click
event on the button and prevent the event's default action mousedown
而不是按钮上的click
事件,并阻止事件的默认操作 See https://stackoverflow.com/a/11787147/96100 . 参见https://stackoverflow.com/a/11787147/96100 。
I typically handle such cases by tracing the cursor change position within the editable control. 我通常通过跟踪可编辑控件中的光标更改位置来处理此类情况。 Set up a variable to hold the last position, update it with each position change, then read the variable from your toolbar's event.
设置一个变量以保留最后一个位置,随着位置的变化对其进行更新,然后从工具栏的事件中读取该变量。
I don't work with JS enough to know the specific syntax for this offhand, but it's pretty general stuff for the most part. 我对JS的了解不够充分,不了解此语法的具体语法,但是在大多数情况下,这是相当普通的东西。
I fixed it with saving the range variable into a window variable (global), after mouseup. 我通过在mouseup之后将range变量保存到window变量(全局)中进行了修复。 Then use this to find and replace the elements.
然后使用它来查找和替换元素。 And it works!
而且有效!
I use this function to define whether a string is selected or not: 我使用此函数来定义是否选择了一个字符串:
function isTextSelected(input) {
var sel,range,selectedText;
if(window.getSelection) {
sel = window.getSelection();
if(sel.rangeCount) {
range = sel.getRangeAt(0);
selectedText = range.toString();
if(selectedText.length) {
window._selection = range; // <-- This line saved my life! :)
return true;
}
}
}
}
And this is the code of the "B" button: 这是“ B”按钮的代码:
$('.editor-icon.b').click(function(e){
var element = document.createElement('b');
var selectedText = document.createTextNode(window._selection.toString());
element.appendChild(selectedText);
window._selection.deleteContents();
window._selection.insertNode(element);
window._selection = false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.