Home  >  Article  >  Web Front-end  >  JavaScript methods and techniques to obtain the selected text on the page_javascript techniques

JavaScript methods and techniques to obtain the selected text on the page_javascript techniques

WBOY
WBOYOriginal
2016-05-16 16:09:451570browse

A little trick introduced here is how to use JavaScript to get the selected text on the page. The most critical JavaScript API is:

Copy code The code is as follows:

event.selection = window.getSelection();

The selection here is actually an object, but if we use .toString() or force conversion to a string, we will get the selected text.
Copy code The code is as follows:

$(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 on the following page:
Copy code The code is as follows:



Get selected text with JavaScript



 



Unlike client-side JavaScript, PHP code runs on the server side. If you set up code similar to the example above on your server, after running the script, the client will receive the results, but they will not know how the code behind it works. You can even set up your web server to let PHP handle all HTML files, so users don't know what the server is actually doing.

One of the great benefits of using PHP is that it is extremely simple for beginners, while also providing a variety of advanced features for professional programmers. Don’t be afraid when you see PHP’s long list of features. You can get started quickly and in just a few hours you can write some simple scripts yourself.





When you select part of the text on the page with the mouse, you will get the selected content at the same time. I use the alert() method here to display it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn