用土办法记忆可编辑 div 内的光标位置
Monday, 5. May 2008, 15:21:12
程序如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>(jQuery) Cursor Position Test </title>
<script type="text/javascript" src="jquery.pack.js"></script>
<style type="text/css" media="all">
#editor {
width:500;
height:100;
margin:10px;
padding:2px;
border:1px solid #0000FF;
overflow:auto;
}
#info {
width:500;
height:200;
margin:10px;
padding:2px;
border:1px solid #00FF00;
background-color:#F8F8F8;
overflow:auto;
}
#caret_pos {
display:none;
cursor:default;
}
</style>
<script type="text/javascript">
function trace(obj) {
if(typeof(obj) == 'object') {
for(var x in obj) {
$('#info').append(x + '<br/>');
}
} else {
$('#info').append(obj + '<br/>');
}
}
$(document).ready(function(){
var caretRange;
//update Caret Pos
function updateCaretPos(e) {
caretRange = document.selection.createRange();
if(caretRange.text != '') {
return;
}
var caretHtml = '<span id="caret_pos"></span>';
if($('#caret_pos').length > 0) {
$('#caret_pos').remove();
}
caretRange = document.selection.createRange();
caretRange.pasteHTML(caretHtml);
caretRange.collapse(true);
}
//insert HTML at Caret Pos
function insertAtCaret(sHtml) {
$('#caret_pos').before(sHtml);
var caret = document.getElementById('caret_pos');
var txtRange = document.body.createTextRange();
txtRange.moveToElementText(caret);
txtRange.select();
}
$('#editor').keyup(function(e){
updateCaretPos(e);
}).click(function(e){
updateCaretPos(e);
}).focus(function(e){
updateCaretPos(e);
});
$('#insert').click(function(e){
insertAtCaret($('#instext').val());
});
$('#editor_html').click(function(e){
$('#info').text($('#editor').html());
});
$('#clear_info').click(function(e){
$('#info').html('');
});
});
</script>
</head>
<body>
<div><h2>Caret Position Test</h2></div>
<div id="editor" contentEditable="true">
<span>start</span>
</div>
<input type="button" id="editor_html" value="Html in Editor" />
<input type="text" id="instext" value="" />
<input type="button" id="insert" value="Insert" />
<div id="info">
</div>
<input type="button" id="clear_info" value="Clear Info" />
</body>
</html>
注:以上程序仅适用于IE。Mozilla系浏览器只需修改pasteHTML部分的代码








