【问题标题】:How to get selected text from DIV using javascript ( working on IE7-8 )?如何使用 javascript(在 IE7-8 上工作)从 DIV 获取选定的文本?
【发布时间】:2011-05-20 05:52:36
【问题描述】:

如何使用 javascript 从 DIV 中获取突出显示的文本?

【问题讨论】:

  • 当您说“选定文本”时,您是指<div> 中的文本还是<div> 中突出显示(选定)的文本?

标签: javascript select html highlight


【解决方案1】:

试试这个:

  

 if (window.getSelection)
 {
     txt = window.getSelection();
 }
 else if (document.getSelection)
 {
     txt = document.getSelection();
 }
 else if (document.selection)
 {
     txt = document.selection.createRange().text;
 }
 else return;

【讨论】:

    【解决方案2】:

    让我们试试吧。

    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Highlighted text</title>
    
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
    if(!window.Kolich){
                    Kolich = {};
                }
    
                Kolich.Selector = {};
                // getSelected() was borrowed from CodeToad at
                // http://www.codetoad.com/javascript_get_selected_text.asp
                Kolich.Selector.getSelected = function(){
                    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;
                }
    
                Kolich.Selector.mouseup = function(){
                    var st = Kolich.Selector.getSelected();
                    if(st!=''){
                        alert("You selected:\n"+st);
                    }
                }
    
                $(document).ready(function(){
                    $(document).bind("mouseup", Kolich.Selector.mouseup);
                });
    </script>
    </head>
    <body>
    Select some text on the page ...
    </body>
    </html>
    

    您可以在此功能上自定义高亮文本的数据。突出显示的文本是st

    Kolich.Selector.mouseup = function () {
        var st = Kolich.Selector.getSelected();
        if (st != '') {
            alert("You selected:\n" + st);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 2010-09-21
      • 2023-01-11
      相关资源
      最近更新 更多