javascript获取选中的文本

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>My JSP 'index.jsp' starting page</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
	</head>

	<body>
		<textarea rows="30" cols="10" name="" id="test"></textarea>
		<div>
		 javascript如何获取鼠标拖黑的文字?也就是我要写个文本编辑器,我在文本域写了”我是个好人”这几个字,然后我用鼠标拖黑选择这”我是个好人”字中的”个好”,然后要把”个好”变黑,,需要怎样通过javascript才能获取”个好”这两个字?
		</div>
	</body>
			<script type="text/javascript">
function getSelectText() {
	var txt = null;
	if (window.getSelection) { // mozilla FF
		txt = window.getSelection();
	} else if (document.getSelection) {
		txt = document.getSelection();
	} else if (document.selection) { //IE
		txt = document.selection.createRange().text;
	}
	return txt;
}
//注意,js代码一定要在id为test的元素下面
var obj = document.getElementById("test");
document.onmouseup = function() {
	obj.value = getSelectText();
}
</script>
</html>

你可能感兴趣的:(JavaScript)