簡體   English   中英

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

[英]Javascript document.all and document.getSelection - Firefox alternative

下面的腳本將替換文本區域中的所選單詞。 但這僅適用於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>

document.all位被用作測試以查看是否為IE。 編寫document.getSelection()的方式將在Firefox中使用,而在IE中將使用document.selection.createRange()

參見http://www.hscripts.com/tutorials/javascript/ternary.php

因此問題不是document.all,而是getSelection()無法正常工作。 不知道為什么不是我最近使用過的那個結構,而是按照以下方法嘗試window.getSelection():(如果不起作用,則嘗試使用google)-http: //www.webdeveloper.com/論壇/歸檔/ index.php文件/ T-138944.html

確定,因此document.getSelection()返回FF中的字符串。 String :: text不存在。 所以你不能設置。

您需要做什么的基礎知識(並且在兩種瀏覽器中都可以使用):

通過其id獲取文本區域-您需要在textarea上設置一個id屬性。 獲取選擇的開始和結束位置。 然后使用三個子字符串:0->開始,開始->結束,結束-> string.length。 將中間子字符串替換為它們在提示中輸入的內容。 將textarea的text設置為新形成的字符串。

具體取決於您的情況,我只是向您介紹了該過程。

我的O'Reilly火烈鳥書正在使用中,但是我似乎還記得閱讀document.getSelection()特別不適用於textarea元素,僅適用於頁面的“不可編輯”部分。

Window.getSelection是在Firefox中使DOMSelection對象可用的方法。 也許這就是您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM