这里介绍的一个小技巧是如何用JavaScript获取页面上被选中的文字的方法。最关键的JavaScript API是:

代码片段
1 行
event.selection = window.getSelection();

这里的selection实际上是个对象,但如果我们使用 .toString()或强行转化成字符串,我们将得到被选中的文字。

GDScript3
12 行
$(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);
				}
			});
		});

如果我们把这段代码放置到下面的页面中:

当用鼠标选中页面中的部分文字,同时你就获取到了选中的内容,我在这里使用alert()方法将其显示出来。