js实现类似微信网页版在可编辑的div中粘贴内容时过滤剪贴板的内容,光标始终在粘贴内容后面,以及将光标定位到最后的方法
Posted on 2015-08-13 15:26 人生梦想起飞 阅读(669) 评论(0) 编辑 收藏 举报过滤剪贴板内容以及定位可编辑div光标的方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="jquery.min.js"></script>
<style type="text/css">
.box{ width:500px; height:300px; border:1px solid #ddd; word-break:break-all; /*支持IE,chrome,FF不支持*/
word-wrap:break-word;/*支持IE,chrome,FF*/white-space:normal; }
</style>
</head>
<body>
<div contenteditable="true" class="box" id="editArea"></div>
<button id="button">光标定位到最后</button>
</body>
</html>
<script type="text/javascript">
$(function(){
$('#editArea').bind('paste',function(){
var e = this, s,
r = e.innerHTML;
s && clearTimeout(s),
s = setTimeout(function() {
for (var c = e.innerHTML, l = -1, u = -1, f = 0, d = c.length; d > f && ( - 1 == l && r.substr(f, 1) != c.substr(f, 1) && (l = f), -1 == u && r.substr(r.length - f - 1, 1) != c.substr(c.length - f - 1, 1) && (u = f), !( - 1 != l && -1 != u || l >= d - 1 - u)); ++f);
if ( - 1 != l && -1 != u) {
if (u = d - 1 - u, l >= u) {
f = l;
for (var g = r.substr(f + 1, 10); ++f < d;) if (g == c.substr(f, g.length)) {
u = f;
break
}
f == d && (u = d - 1)
}
"<" == c.substr(l - 1, 1) && --l,
">" == c.substr(u + 1, 1) && ++u;
var m = c.substring(l, u + 1),
p = c.substr(0, l),
h = c.substr(l + m.length),
M = p.lastIndexOf("<"),
y = p.lastIndexOf(">");
if (M > y && (m = p.slice(M) + m, p = p.slice(0, M)), M = m.lastIndexOf("<"), y = m.lastIndexOf(">"), M > y) {
var C = h.indexOf(">") + 1;
m += h.slice(0, C),
h = h.slice(C)
}
var _ = m.replace(/<[^>]+>/g, "");
e.innerHTML = p + _ + "<span class='pasteCaretPosHelper'></span>" + h;
var v, w, S = $(e).find(".pasteCaretPosHelper")[0];
S && (document.createRange ? (v = document.createRange(), v.setStartAfter(S), v.collapse(!1), w = window.getSelection(), w.removeAllRanges(), w.addRange(v)) : document.selection && (v = document.body.createTextRange(), v.moveToElementText(S), v.collapse(!1), v.select()), S.parentNode.removeChild(S))
}
},50)
})
$('#button').click(function(){
po_Last_Div('editArea')
})
})
function po_Last_Div(obj) {
var obj = document.getElementById(obj);
if (window.getSelection) {//ie11 10 9 ff safari
obj.focus(); //解决ff不获取焦点无法定位问题
var range = window.getSelection();//创建range
range.selectAllChildren(obj);//range 选择obj下所有子内容
range.collapseToEnd();//光标移至最后
}
else if (document.selection) {//ie10 9 8 7 6 5
var range = document.selection.createRange();//创建选择对象
//var range = document.body.createTextRange();
range.moveToElementText(obj);//range定位到obj
range.collapse(false);//光标移至最后
range.select();
}
}
</script>
缺陷:此方法粘贴时如果连续粘贴会导致光标最后定位出现错误,如果不是连续粘贴同一个剪贴板上的内容不会出现错误,不过,虽然光标位置错误,但是内容粘贴的是正确。这个问题微信网页版同样存在