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; //文字浮标选择的结束位置
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- JS 在数组插入字符的实现代码(可参考JavaScript splice() 方法)
- JS 的应用开发初探(mootools)
- 用js实现层随着内容大小动态渐变改变 推荐
- javascript demo 基本技巧
- javascript option onclick事件ie解决方案 兼容ie,firefox
- IE和Firefox下event事件杂谈
- div+css+js模拟tab切换效果 事件绑定 IE,firefox兼容
- 替代window.event.srcElement效果的可兼容性的函数
- JavaScript 序列化对象实现代码
- 让div层随鼠标移动的实现代码 ie ff
- Javascript 多浏览器兼容性问题及解决方案
- Javascript在IE或Firefox下获取鼠标位置的代码
- javascript DOM操作之动态删除TABLE多行
- javascript 导出数据到Excel(处理table中的元素)
- event.srcElement 用法笔记e.target
- javascript获得光标所在的文本框(text/textarea)中的位置
- [原创]javascript 移动鼠标得到单元格所在table表中的rowIndex位置[兼容ie,firefox]
- Javascript document.referrer判断访客来源网址
- jQuery Attributes(属性)的使用(二、类篇)