文本选择不起作用

text selection is not working

本文关键字:不起作用 选择 文本      更新时间:2023-09-26

我想实现这一点,当我在页面上选择一些文本,然后点击一个按钮,我可以通过javascript获得这些文本。

function getSelText()
    {
        var t = '';
        if(window.getSelection){
            t = window.getSelection();
        }else if(document.getSelection){
            t = document.getSelection();
        }else if(document.selection){
            t = document.selection.createRange().text;
        }
        return t;
    }

我有这个功能,但它不起作用。

self.Copy = function () {
        alert(getSelText());
    }

复制功能正在工作,但警报的结果始终为空。

此代码适用于我:

<html>
<head>
    <script type="text/javascript">
        function TestSelection () {
            if (window.getSelection) {  
                var selectionRange = window.getSelection ();                                        
                alert ("The text content of the selection:'n" + selectionRange.toString ());
            } 
            else {
                if (document.selection.type == 'None') {
                    alert ("No content is selected, or the selected content is not available!");
                }
                else {
                    var textRange = document.selection.createRange ();
                    alert ("The text content of the selection:'n" + textRange.text);
                }
            }
        }
    </script>
</head>
<body>
    Select some text or <button>element</button>, or do not select anything, before you click on the button below.
    <br /><br />
    <button onclick="TestSelection ();">Test the selection!</button>
</body>
</html>