在Firefox下怎么实现如下代码的功能,即在焦点处插入文本?
- <!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-Type" content="text/html;">
- </head>
- <body>
- <input type="button" onclick="abc()" value="ok">
- <input type="text" name="text1" id="text1" value="你好,天气不错">
- </body>
- </html>
- <SCRIPT LANGUAGE="JavaScript">
- <!--
- function abc(){
- if(document.selection){
- text1.focus();var range=document.selection.createRange();range.text='今天';
- }
- else{
- var textBox=document.getElementById("text1");
- var start = textBox.selectionStart;
- var end = textBox.selectionEnd;
- var pre = textBox.value.substr(0, start);
- var post = textBox.value.substr(end);
- textBox.value = pre + '今天' + post;
- }
- }
- //-->
- </SCRIPT>
- 稍微解释一下,在IE下很简单:首先得到焦点所在输入框的引用,然后document.selection.createRange();为光标创建一个对象,将值赋给他就行了。
- 而在Firefox下,我们需要得到光标前的内容和后的内容,再把数据插入到内容中间!