简体   繁体   English

window.getSelection“重新选择” /“刷新”

[英]window.getSelection “reselect”/“refresh”

I try build toolbar for editable html elements. 我尝试为可编辑的html元素构建工具栏。 I have toolbar with "bold","italic" and others. 我有带有“粗体”,“斜体”等的工具栏。

When user was selected any text and clicked "bold" I check does exists span and insert if not. 当选择用户任何文本并单击“粗体”时,我检查是否存在跨度,如果没有则插入。

let hasWrap = (selectionObject.node==='SPAN');

if(!isBold){

  this.addClassToSelection('bold', !hasWrap, selectionObject);

}

addClassToSelection(className, wrapSpan = false, selectionObject = {}){

if(wrapSpan){
  let wrapper = document.createElement('SPAN');
  wrapper.className = className;
  wrapper.textContent = selectionObject.text;

  selectionObject.range.deleteContents();
  selectionObject.range.insertNode(wrapper);
}else{
  let selection = window.getSelection();
  selection.anchorNode.parentNode.classList.add(className);
}

} }

And it works. 而且有效。 Also it works perfect if user will deselect text and select again. 如果用户取消选择文本并再次选择,它也可以完美地工作。

But when user add bold (and js insert span element) and next click again "bold" to remove bold. 但是,当用户添加粗体(并且js插入span元素),然后再次单击“粗体”以删除粗体时。 System doesn't detect "span" element because still remember old window.getSelection() . 系统未检测到“ span”元素,因为仍记得旧的window.getSelection()

I've been tried use window.getSelection() directly without wrap in method but still I see "p" or "div" as parent node. 我已经尝试过直接使用window.getSelection()而没有使用wrap方法,但是我仍然看到“ p”或“ div”作为父节点。 "span" is after select this text again. 再次选择此文本后,将显示“ span”。

How can I "reselect" this text to detect span but without user action. 如何“重新选择”此文本以检测跨度,但没有用户操作。

What I'd like 我想要什么

  1. user is selecting text 用户正在选择文本
  2. User is clicking "bold" button 用户单击“粗体”按钮
  3. system wrap text in span with bold class 系统使用粗体类将文本换行
  4. user click "bold" button again and window.getSelection detect this span inserted in point 3 用户再次单击“粗体”按钮,window.getSelection检测到该跨度插入点3

I use React in ES6 and I'd like use plain js without jQuery (wrap,unwrap). 我在ES6中使用React,我想在不使用jQuery的情况下使用普通js(wrap,unwrap)。

 <div contenteditable="true">Make bold with Ctrl+b</div> 

Would be much better to use document.execCommand - window.getSelection is much harder 使用document.execCommand会更好-window.getSelection难得多

HTML HTML

<div contenteditable="true">Some Text</div>

JS - when custom event handling is required JS-需要自定义事件处理时

document.execCommand('bold',false,true);

see the list of commands here : https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand 请在此处查看命令列表: https : //developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand

and an "How To Use" here : http://codepen.io/netsi1964/full/QbLLGW/ 以及此处的“使用方法”: http : //codepen.io/netsi1964/full/QbLLGW/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM