文字选择无效

时间:2012-02-07 14:38:00

标签: javascript dom

我希望实现这一点,当我在我的页面上选择一些文本然后点击一个按钮,我通过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());
    }

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

1 个答案:

答案 0 :(得分:0)

这段代码对我有用:

<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>