textbox 在光标位置插入字符功能的js实现(兼容ie,firefox)

  作者:bea

<?xml version="1.0" encoding="gb2312"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> &l


<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Language" content="zh-cn" />
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>更简单的在光标处插入文字</title>
</head>
<body>
<form method="get">
<div><textarea id="content" cols="50" rows="5">先在本文框中点鼠标以确定光标位置。</textarea></div>
<div><input type="button" value="插入文字"A"" onclick="javascript:Insert('A');" /></div>
<div><input type="button" value="插入文字"B"" onclick="javascript:Insert('B');" /></div>
</form>
<script type="text/javascript" language="javascript">
<!--

function Insert(str) {
var obj = document.getElementById('content');
if(document.selection) {
obj.focus();
var sel=document.selection.createRange();
document.selection.empty();
sel.text = str;
} else {
var prefix, main, suffix;
prefix = obj.value.substring(0, obj.selectionStart);
main = obj.value.substring(obj.selectionStart, obj.selectionEnd);
suffix = obj.value.substring(obj.selectionEnd);
obj.value = prefix + str + suffix;
}
obj.focus();
}
-->
</script>
</body>
</html>




[Ctrl+A 全选 注:
如需引入外部Js需刷新才能执行]

需要注意的是
document.selection.createRange是IE独有的
而firefox也有独有的一套


代码如下:


var $obj = document.getElementById("words");
var selstart = $obj.selectionStart; //文字浮标选择的开始位置
var selend = $obj.selectionEnd; //文字浮标选择的结束位置




有用  |  无用

猜你喜欢