Kel*_*Lim 5 html javascript html5 contenteditable
我正在尝试编写一个函数,允许一个contenteditable div在用户输入div时进行一些自动格式化.到目前为止,我只能让它在IE中运行.有人可以帮帮我吗?
function formatOnKeyUp(){
if (window.getSelection) {
// ???????
} else if (document.selection) {
cursorPos=document.selection.createRange().duplicate();
clickx = cursorPos.getBoundingClientRect().left;
clicky = cursorPos.getBoundingClientRect().top;
}
text = document.getElementById('div1').innerHTML;
text = text.replace(/this/gm, "<i>this</i>");
// .... some other formating here...
document.getElementById('div1').innerHTML = text;
if (window.getSelection) {
// ????????
} else if (document.selection) {
cursorPos = document.body.createTextRange();
cursorPos.moveToPoint(clickx, clicky);
cursorPos.select();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用我的Rangy库中的选择保存和恢复模块,该模块在选择边界处使用不可见的标记元素。我还建议在键盘不活动一段时间后进行更换,而不是在每次活动时进行更换:keyup
function formatText(el) {
// Save the selection
var savedSel = rangy.saveSelection();
// Do your formatting here
var text = el.innerHTML.replace(/this/gm, "<i>this</i>");
el.innerHTML = text;
// Restore the original selection
rangy.restoreSelection(savedSel);
}
var keyTimer = null, keyDelay = 500;
document.getElementById('div1').onkeyup = function() {
if (keyTimer) {
window.clearTimeout(keyTimer);
}
keyTimer = window.setTimeout(function() {
keyTimer = null;
formatText(document.getElementById('div1'));
}, keyDelay);
};
Run Code Online (Sandbox Code Playgroud)