javascript获取以及设置光标位置

一. 获取光标位置:

rush:js;"> // 获取光标位置 function getCursortPosition (textDom) { var cursorPos = 0; if (document.selection) { // IE Support textDom.focus (); var selectRange = document.selection.createrange(); selectRange.moveStart ('character',-textDom.value.length); cursorPos = selectRange.text.length; }else if (textDom.selectionStart || textDom.selectionStart == '0') { // Firefox support cursorPos = textDom.selectionStart; } return cursorPos; }

二. 设置光标位置:

rush:js;"> // 设置光标位置 function setCaretPosition(textDom,pos){ if(textDom.setSelectionRange) { // IE Support textDom.focus(); textDom.setSelectionRange(pos,pos); }else if (textDom.createTextRange) { // Firefox support var range = textDom.createTextRange(); range.collapse(true); range.moveEnd('character',pos); range.moveStart('character',pos); range.select(); } }

三. 获取中文字:

rush:js;"> // 获取中文字 function getSelectText() { var userSelection,text; if (window.getSelection) { // Firefox support userSelection = window.getSelection(); } else if (document.selection) { // IE Support userSelection = document.selection.createrange(); } if (!(text = userSelection.text)) { text = userSelection; } return text; }

四. 选中特定范围的文本:

textLength){ startPos = textLength; } if(endPos > textLength){ endPos = textLength; } if(startPos < 0){ startPos = textLength + startPos; } if(endPos < 0){ endPos = textLength + endPos; } if(textDom.createTextRange){ // IE Support var range = textDom.createTextRange(); range.moveStart("character",-textLength); range.moveEnd("character",-textLength); range.moveStart("character",startPos); range.moveEnd("character",endPos); range.select(); }else{ // Firefox support textDom.setSelectionRange(startPos,endPos); textDom.focus(); } } }

五. 在光标后插入文本:

rush:js;"> /** * 在光标后插入文本 * 参数: * textDom [JavaScript DOM String] 当前对象 * value [String] 要插入的文本 */ function insertAfterText(textDom,value) { var selectRange; if (document.selection) { // IE Support textDom.focus(); selectRange = document.selection.createrange(); selectRange.text = value; textDom.focus(); }else if (textDom.selectionStart || textDom.selectionStart == '0') { // Firefox support var startPos = textDom.selectionStart; var endPos = textDom.selectionEnd; var scrollTop = textDom.scrollTop; textDom.value = textDom.value.substring(0,startPos) + value + textDom.value.substring(endPos,textDom.value.length); textDom.focus(); textDom.selectionStart = startPos + value.length; textDom.selectionEnd = startPos + value.length; textDom.scrollTop = scrollTop; } else { textDom.value += value; textDom.focus(); } }

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程之家!

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...