JavaScript ------- 文本内容 选择 (高级程序设计)

来源:互联网 发布:qq飞车神影官方数据 编辑:程序博客网 时间:2024/06/06 04:02

<html>
<head>
<title>文本选择</title>
</head>

<body>

<form  name="form">

<textarea name="textbox" rows="25" cols="5">0123456789</textarea>

</form>

</body>
</html>

获取html 背景颜色 的值

1.选择文本 

使用 select() 方法  触发场景:  用户选择了文本(而且要释放鼠标),才会触发此事件

//取到textarea

var textbox=document.form.elements["textbox"];

textbox.addEventListener("select",function(){

console.log("触发了select事件")

})

2.取得选中的文本值

有2个属性 selectionStart (选中的头),selectionEnd(选中的尾)    //返回值类型为 number

//获取文本值

textbox.addEventListener("select",function(event){

var target=event.target;

//输出 345678

console.log(target.value.substring(target.selectionStart,target.selectionEnd))

})

//IE 8 及以下 无法兼容上述方法 所以 有自己的特有方法 document.selection 建一个兼容的方法function getSelectionText(textbox){

if(typeof textbox.selectionStart == "number"){
return textbox.value.substring(textbox.selectionStart,textbox.selectionEnd);
}else if(document.selection){
return document.selection.createRange().text;
}

}