<div class="textarea textareaplace" id="userinfo" contenteditable="true" onkeydown="keyD(this);" onkeyup="keyAction(this);" oncopy="keyCop();" onpaste="keyPas()"></div>
js代码
var textbox = document.getElementById('userinfo'),
g_selectNum=0,
sel = window.getSelection(),
range = document.createRange();
function keyD(obj){ //按下事件
var a=textbox.innerHTML;
var textA=textbox.innerText.substr(0,20);
range.selectNodeContents(textbox); //将div节点内容加进range内
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range); //j将range对象加入文本域
}
function keyPas(){
var textA=textbox.innerText.substr(0,20);
setTimeout(function(){
var a=textbox.innerHTML;
textbox.innerText=a.replace(/<span.*">|</span>/g, ""); //将复制内容中span标签替换
range.selectNodeContents(textbox);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
},300)
};
function keyCop(obj){
var textA=textbox.innerText.substr(0,20);
a_num=textA.length;
var selectCon=sel.toString();
g_selectNum=selectCon.length;
}
function keyAction(obj) {
var textA=textbox.innerText.substr(0,20);
a_num=textA.length;
a_arr[1]=a_num;
textbox.innerText=textA;
range.selectNodeContents(textbox);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}