【问题标题】:Capture the highlighted text in textbox for Mozilla Browser [duplicate]在 Mozilla 浏览器的文本框中捕获突出显示的文本 [重复]
【发布时间】:2012-07-13 10:45:01
【问题描述】:

可能重复:
Understanding what goes on with textarea selection with JavaScript
Copy and paste the selected text to the clipboard using JavaScript

我有点困惑我应该如何处理这个问题,我在这个区域有一个文本框,我希望用户能够突出显示文本框中的一个单词。我需要捕捉突出显示的单词。它适用于除 Mozilla 之外的所有浏览器。

我在这里使用 onkeydown 事件。

var startPos = textComponent.selectionStart;        
var endPos = textComponent.selectionEnd;

selected = textComponent.value.substring(startPos,endPos);

这是我用于 Mozilla 的代码。它不工作。

请帮帮我

【问题讨论】:

  • 只要选择确实存在,该代码就可以在 Mozilla 浏览器中运行。你什么时候调用这个代码?几乎可以肯定,在调用代码时选择不存在。

标签: javascript cross-browser


【解决方案1】:

使用谷歌了一下,发现这个:http://www.codeproject.com/Articles/292159/Javascript-code-to-get-selected-text不确定是否有效,但可能有帮助:)

【讨论】:

  • 看看朋友。谢谢
  • 对不起,伙计。它也不起作用
  • 实现此目的的任何其他方式
【解决方案2】:
Howvever, I managed to fix this by this code. Please use this below coding for capturing the textbox selected value.

<**head>
    <script type="text/javascript">
        function GetSelectedText () {
            var selText = "";
            if (window.getSelection) {  // all browsers, except IE before version 9
                if (document.activeElement && 
                        (document.activeElement.tagName.toLowerCase () == "textarea" || 
                         document.activeElement.tagName.toLowerCase () == "input")) 
                {
                    var text = document.activeElement.value;
                    selText = text.substring (document.activeElement.selectionStart, 
                                              document.activeElement.selectionEnd);
                }
                else {
                    var selRange = window.getSelection ();
                    selText = selRange.toString ();
                }
            }
            else {
                if (document.selection.createRange) { // Internet Explorer
                    var range = document.selection.createRange ();
                    selText = range.text;
                }
            }
            if (selText !== "") {
                alert (selText);
            }
        }
    </script>
</head>
<body onmouseup="GetSelectedText ()">
    Some text for selection.
    <br /><br />
    <textarea>Some text in a textarea element.</textarea>
    <input type="text" value="Some text in an input field." size="40"/>
    <br /><br />
    Select some content on this page!
</body>**

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 2016-11-14
    • 2010-09-19
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多