Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[html] 第120天 你知道富文本编辑器的实现原理吗? #1061

Open
haizhilin2013 opened this issue Aug 13, 2019 · 5 comments
Open
Labels
html html

Comments

@haizhilin2013
Copy link
Collaborator

第120天 你知道富文本编辑器的实现原理吗?
趁热打铁,昨天也出了一道类似的题 #1057

@haizhilin2013 haizhilin2013 added the html html label Aug 13, 2019
@LinStan
Copy link

LinStan commented Aug 14, 2019

按自己想法来大概推理的话 应该是通过设置iframe或者frame,然后每个按钮上绑定不同的点击事件,通过点击按钮可以对容器中的部分文本修改其样式。

@ghost
Copy link

ghost commented Aug 14, 2019

总结一下技术难点:

  • 原生 <textarea> 没法显示带格式的文本;因此只能:
    • <div>
    • 在点击输入框时,通过 HTMLElement.focus() 聚焦到到一个隐藏的 <input> 上,通过监听 oninput 来获得用户输入。
  • 存储格式,可以使用 json;
  • 用户点击输入框的不同位置时通过 e.offsetXe.offsetY 来实现定位光标。

@xxf1996
Copy link

xxf1996 commented Aug 14, 2019

  1. contenteditable(HTML)属性:一个全局枚举属性,用于表示元素是否可编辑;该属性可被继承。
  2. caret-color(CSS)属性:可设置编辑区域内的可插入光标的颜色;
  3. Window.getSelection()方法:返回一个Selection对象,表示用户选择的文本范围或光标的当前位置;利用该方法可以对选中的文字进行样式设置,或在光标处插入内容等操作。

大概想到的就是这些;

参考文档:

@XboxYan
Copy link

XboxYan commented Aug 15, 2019

富文本编辑器基本上都是调用这个指令,完全不需要手动判断选中区域

document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

比如

document.execCommand('bold',false'); 
//切换选中区域的粗体样式

详情可参考 execCommand

@zhaofeipeter
Copy link

用iframe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
html html
Projects
None yet
Development

No branches or pull requests

5 participants