jquery实现简单富文本编辑
<script>
$("#under").click(function () {
var sec = getSelection()
if (sec == undefined) {
return;
}
ReplaceInnerHtml(sec.selectStr, GetSelectedStyle(sec.dom,'text-decoration', 'underline'));
})
$("#bold").click(function () {
var sec = getSelection();
if (sec == undefined) {
return;
}
ReplaceInnerHtml(sec.selectStr, GetSelectedStyle(sec.dom,'font-weight','bold'));
})
$("#big").click(function () {
var sec = getSelection()
if (sec == undefined) {
return;
}
ReplaceInnerHtml(sec.selectStr, GetSelectedStyle(sec.dom,'font-size','18px'));
})
$("#small").click(function () {
var sec = getSelection()
if (sec == undefined) {
return;
}
ReplaceInnerHtml(sec.selectStr, GetSelectedStyle(sec.dom,'font-size','14px'));
})
function getSelection() {
var selectStr = window.getSelection().toString();
if (selectStr == '')
return undefined;
var dom = window.getSelection().getRangeAt(0).commonAncestorContainer;
if ($("#content").find(dom).length == 0) {
return undefined;
}
return { selectStr: selectStr,dom:dom}
}
function GetSelectedStyle(dom,key,value) {
var style = '';
if ($(dom).prop('nodeName') == 'SPAN') {
style = $(dom).attr('style');
}
else if ($(dom).parent().prop('nodeName') == 'SPAN') {
style = $(dom).parent().attr('style');
}
if (style == undefined) {
style = '';
}
style = style.replace(' ', '');
if (key == '' || key == undefined) {
return style;
}
var styleList = style.split(';');
var item = styleList.find(a => a.indexOf(key) > -1)
if (item != undefined) {
for (var i = 0; i < styleList.length; i++) {
if (styleList[i].indexOf(key) > -1) {
if (value == '') {
styleList[i] = '';
}
else {
styleList[i] = key + ':' + value;
}
}
}
}
else {
styleList.push(key + ':' + value)
}
styleList = styleList.filter(a => a != '');
styleList.push('');
return styleList.join(';');
}
function ReplaceInnerHtml(html, style) {
document.execCommand('insertHTML', 'false', '<span id="' + id + '" style="' + style + '">' + html + '</span>');
const range = window.getSelection().getRangeAt(0)
const dom = document.getElementById(id)
range.setStart(dom, 0)
range.setEnd(dom, 1)
id++;
}
</script>
<div style="width:200px;height:200px;margin:auto" class="body">
<button id="under">下划线</button>
<button id="bold">加粗</button>
<button id="big">大</button>
<button id="small">小</button>
<select id="size">
<option>9px</option>
<option>14px</option>
<option>18px</option>
</select>
<div id="content">
<div class="text" contenteditable="true">
65666666666666666666666666
</div>
</div>
</div>