Get selected text on IPad 2 with Javascript

2019-05-28 20:54发布

问题:

I'am developing a web-application that allows to select parts of an html document and put some kind of annotation on it. To get hold of the selected text I use window.getSelection() which works pretty fine in IE9, FF, and Safari. However I run into trouble when using the same page on my IPad 2:

  • If I just select a word by tapping it for a sec, window.getSelection() returns the proper selection.
  • If I create a text range ( as discribed here http://blog.laptopmag.com/how-to-select-copy-and-paste-text-on-the-ipad ) always return "null". I've already examined the window, document and related event objects - but without success...

Any help would be really appreciated!

Edit: Just a small example. Select a text and press the button. On Safari (PC) the function prints the selected value...

<html>
    <body>
        <script>
            function a() 
            {
                alert(window.getSelection());
            }
        </script>
        Hello World! <input type="button" onclick="a();"
    </body>
</html>

回答1:

Okay finally I've solved the problem: As Tim assumed the click events causes to selection to collapse. I consider this as rather strange behavior as on regular Safari this does not happen.

However, the solution is not to use the click event. Instead of I'm using "vlick" provided by the jquery mobile.

Full working example:

<!DOCTYPE html> 
<html> 
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
</head>
<body> 
    Hello World! <input type="button"  id="button1" /> 

    <script> 
        function a()  
        { 
            alert(window.getSelection()); 
        } 

        $("#button1").bind("vclick",a);
    </script>       
</body> 
</html>