Tips for using JavaScript to retrieve selected text on the page
The tips here are how to use JavaScript to obtain the selected text on the page. The most critical JavaScript API is:
Event. selection = window. getSelection ();
Hereselection
It is actually an object, but if we use .toString()
Or forcibly convert it into a string, we will get the selected text.
- $(document).ready(function () {
- $(".contenttext").mouseup(function (e) {
- var txt;
- var parentOffset = $(this).offset();
- var x = e.pageX - parentOffset.left;
- var y = e.pageY - parentOffset.top;
- txt = window.getSelection();
- if (txt.toString().length > 1) {
- alert(txt);
- }
- });
- });
If we place this Code in the following page:
- <Html>
- <Head>
- <Title> Get selected text with JavaScript </title>
- <Meta charset = "UTF-8">
- <Meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
- <Script src = "http://www.webhek.com/wordpress/wp-includes/js/jquery/jquery.js" type = "text/javascript"> </script>
- </Head>
- <Body>
- <Div class = "contenttext">
- Unlike JavaScript on the client, PHP code runs on the server. If you have created code similar to the preceding example on your server, the client will receive the result after running the script, but they cannot know how the code behind it works. You can even set the WEB server to PHP to process all HTML files, so that users cannot know what the server has done.
-
- One of the major advantages of using PHP is its simplicity for beginners. It also provides various advanced features for professional programmers. Do not be afraid when you see a long PHP feature list. You can get started quickly and write some simple scripts by yourself in just a few hours.
- </Div>
- </Body>
- </Html>
When you select some text on the page with the mouse, you can get the selected content.alert()
Method.