用JavaScript获取页面上被选中的文字的技巧

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

event.selection = window.getSelection();

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

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

  

原文地址:https://www.cnblogs.com/xupeiyu/p/4942466.html