相关知识点
textatea 输入框特点
- 具有默认的宽度和高度,输入内容到边会自动换行,可设置 white-space:pre; 使其水平不会自动换行除非按下enter键。
- 无论是否设置高度,输入内容高度超过会出现滚动条,可监听其 scrollHeight 使其高度随内容高度自适应。
- 输入中按下enter换行时根据浏览器不同会在光标处插入换行符 ‘/r/n’ 或 ‘/n’。
- 插入的 html 代码都会被转义
1.高度自适应
<textarea id="text"></textarea>
<script>
var text = document.getElementById("text")
text.oninput = function(){
//高度自适应
this.style.height = 'auto'
if(this.scrollHeight > this.offsetHeight){
this.style.height = this.scrollHeight + "px"
}
//宽度自适应,前提设置 white-space:pre;
this.style.width = 'auto'
if(this.scrollWidth > this.offsetWidth){
this.style.width = this.scrollWidth + "px"
}
}
</script>
2.获取光标位置
function getCP (el) {
el.focus ();
if (document.selection) {
//低版本IE
var range = document.selection.createRange();
range .moveStart ('character', -el.value.length);
return range.text.length;
}else if (el.selectionStart != null ){
//有些input类型不支持,过滤
return el.selectionStart;
}
}
3.设置光标位置
/*
* el 输入框元素
* pos 位置下标,若为'last'则移动到末尾
*/
function setCP(el, pos){
el.focus();
if(pos == 'last'){
pos = el.value.length
}
if(el.setSelectionRange) {
el.selectionStart = el.selectionEnd = pos;
}else if (el.createTextRange) {
//IE低版本浏览器
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
4.获取选中的文本:可以获取页面任何元素中被鼠标选中的内容,不仅仅是输入框。
function getSelectText() {
if (document.selection) {
//低版本IE
return document.selection.createRange().text;
}else{
return window.getSelection().toString();
//return el.value.substring(el.selectionStart,el.selectionEnd);
}
}
5.选中特定范围的文本