Home > Web Front-end > JS Tutorial > Let's take a look at how JavaScript gets the selected text on the page

Let's take a look at how JavaScript gets the selected text on the page

coldplay.xixi
Release: 2020-06-20 17:08:52
forward
2371 people have browsed it

Let's take a look at how JavaScript gets the selected text on the page

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

event.selection = window.getSelection();
Copy after login

The selection here is actually an object, but if we use .toString() or force conversion to a string, we The selected text will be obtained.

$(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);
				}
			});
		});
Copy after login

If we place this code into 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>
				<p class="contenttext">
					和客户端的 JavaScript 不同的是,PHP 代码是运行在服务端的。如果您在您的服务器上建立了如上例类似的代码,则在运行该脚本后,客户端就能接收到其结果,但他们无法得知其背后的代码是如何运作的。您甚至可以将 WEB 服务器设置成让 PHP 来处理所有的 HTML 文件,这么一来,用户就无法得知服务端到底做了什么。 

					使用 PHP 的一大好处是它对于初学者来说及其的简单,同时也给专业的程序员提供了各种高级的特性。当您看到 PHP 长长的特性列表时,请不要害怕。您可以很快的入门,只需几个小时您就可以自己写一些简单的脚本。 
				</p>
			</body>
		</html>
Copy after login

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 it here alert() method displays it.

Lets take a look at how JavaScript gets the selected text on the page

The above is the detailed content of Let's take a look at how JavaScript gets the selected text on the page. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:webhek.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template