JS 如何实现按下Esc按键全选文本框中的文本内容?

JavaScript08

JS 如何实现按下Esc按键全选文本框中的文本内容?,第1张

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<div>文本框:</div>

<textarea>按下ESC选中我</textarea>

<script src="jquery.min.js" ></script>

<script type="text/javascript">

function hotkey()

{

var a=window.event.keyCode

if(a==27)

{

$('textarea').select()

}

}

// 初始化加载

$(document).ready(function () {

document.onkeydown = hotkey

})

</script>

</body>

</html>

有如下的文本框:

<input name="jbxue_form" id="jbxue_form" value="内容" /> <script>

//JS选中文本框中内容

document.getElementById("jbxue_form").focus()

document.getElementById("jbxue_form").select()

//jquery选中文本框中内容

$("#jbxue_form").focus()

$("#jbxue_form").select()

</script>

function func(){

var textarea = document.getElementById("textarea")

//首先移动光标到所选文字位置,滚动条自动滚动

MoveCursortoPos('textarea' , 30 )

//再选中文字

textarea.setSelectionRange(30,32)//选中文本框内的文字

//textarea.scrollTop = textarea.scrollHeight//滚动到底部

//想要修改成只滚动到 选中文字 的位置应该怎么写?

}

//设置光标位置

function MoveCursortoPos(id,pos){//定位光标到某个位置

var obj = document.getElementById(id)//获得元素

pos = pos ?pos :obj.value.length

if (obj.createTextRange) {//IE浏览器 IE浏览器中有TextRange 对body,textarea,button有效

var range = obj.createTextRange()//创建textRange

range.moveStart("character", pos)//移动开始点,以字符为单位

range.collapse(true)//没有移动结束点直接 折叠到一个点

range.select()//选择这个点

} else {//非IE浏览器

obj.setSelectionRange(obj.value.length, pos)

}

obj.focus()

}