Javascript document.all和document.getSelection - Firefox替代方案

时间:2009-04-15 01:30:25

标签: javascript cross-browser

下面的脚本将替换textarea中的选定单词。但它只适用于IE。知道如何让它在Firefox上运行吗? (问题似乎在于(document.all)?document.selection.createRange():document.getSelection();)

<SCRIPT LANGUAGE="JavaScript">
    <!--//
    var seltext = null;
    var repltext = null;
    function replaceit() 
    {
        seltext = (document.all)? document.selection.createRange() : document.getSelection();
        var selit = (document.all)? document.selection.createRange().text : document.getSelection();
        if (selit.length>=1){
            if (seltext) {
                repltext= prompt('Please enter the word to replace:', ' '); 
                if ((repltext==' ')||(repltext==null)) repltext=seltext.text;
                seltext.text = repltext;
                window.focus()
            }
        }
    }
    //-->
</SCRIPT>
</HEAD>
<BODY>
    <form name="f">
        <textarea cols='40' rows='10' name='msg'></textarea>

        <input type="button" name="b" value="Replace" onClick="replaceit();">
    </form>
</BODY>

4 个答案:

答案 0 :(得分:2)

document.all位用作测试以查看它是否为IE。它的编写方式是document.getSelection(),它将在Firefox中使用,IE中的document.selection.createRange()

请参阅 http://www.hscripts.com/tutorials/javascript/ternary.php

所以问题不是document.all,而是getSelection()不起作用。不确定为什么这不是我最近使用过的构造,但是按照这样的方式尝试window.getSelection():(如果不能做到这一点,请谷歌等其他人) http://www.webdeveloper.com/forum/archive/index.php/t-138944.html

答案 1 :(得分:1)

好的,所以document.getSelection()在FF中返回一个字符串。 String :: text不存在。所以你不能设置它。

您需要做什么的基本想法(并且它将在两种浏览器中都有效):

通过id获取文字区域 - 您需要在textarea上设置id属性。获取选择的起始位置和结束位置。然后取三个子串:0-> start,start-&gt; end,end-&gt; string.length。将中间子字符串替换为它们在提示中放置的内容。将textarea的text设置为新形成的字符串。

确切的由你决定,我只是给你一个程序的味道。

答案 2 :(得分:0)

我的O'Reilly火烈鸟书正在发挥作用,但我似乎记得阅读该文档.getSelection()特别适用于textarea元素,只适用于页面的“不可编辑”部分。

答案 3 :(得分:0)

Window.getSelection是使firefox中的DOMSelection对象可用的方法。也许这就是你要找的东西。