富文本的实现

环境

chrome浏览器

代码

$richedit = document.getElementById('section');
$richedit.contentEditable = 'true';

开启contenteditable后就可以编辑id为section的区域了

可以粘贴图片,会在代码中插入Base64编码

富文本的操作

document.execCommand(value1,value2,value3)

js提供了对应的API,例如加粗

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

bold 加粗

italic 斜体

justifycenter 居中对齐
insertimage false url 插入图片 
fontsize false size 字体大小
 
精准控制
var selection = document.getSelection();
console.log('当前选中的文本:');
console.log(selection.toString());

// 取得代表选区的范围                                                
var range = selection.getRangeAt(0);
console.log(range);
// 包裹一个标签使得选中内容突出
var span = document.createElement('span');
span.style.backgroundColor = '#f0f';
range.surroundContents(span);

console.log('当前文本编辑器内容:');
console.log($richedit.innerHTML);

 

posted @ 2020-06-15 16:40  Fan式编程  阅读(306)  评论(0编辑  收藏  举报