简体   繁体   中英

How to get selected text from DIV using javascript ( working on IE7-8 )?

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

Try this:

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

Let's try.

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

You can customize the data of highlighted text on this function. The highlighted text is st

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM