js获取编辑框游标的位置

代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>js获取编辑框游标的位置</title>
    <script src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        //去除左右所有空格
        String.prototype.trim = function () {
            return this.replace(/(^\s*)|(\s*$)/g, "");
        }
        function getPosition(element) {
            var OsObject = "";
            if (navigator.userAgent.indexOf("MSIE") > 0) {
                OsObject = "MSIE";
            }
            if (navigator.userAgent.indexOf("Firefox") > 0) {
                OsObject = "Firefox";
            }
            if (navigator.userAgent.indexOf("Safari") > 0) {
                OsObject = "Safari";
            }
            if (navigator.userAgent.indexOf("Camino") > 0) {
                OsObject = "Camino";
            }
            if (navigator.userAgent.indexOf("Gecko") > 0) {
                OsObject = "Gecko";
            }
            if (navigator.userAgent.indexOf("Chrome") > 0) {
                OsObject = "Chrome";
            } 

            var result = 0;
            if (!document.selection) { //非IE浏览器
                var thisTagName = null;
                if ($(element)[0].nodeName != "TEXTAREA" && $(element)[0].nodeName != "INPUT") {
                    if ($(element)[0].nodeName == "DIV" && $(element).attr("contenteditable") == "true") {
                        thisTagName = window.getSelection().anchorNode.parentElement.tagName;
                    }
                    else {
                        thisTagName == null;
                    }
                }
                else {
                    if ($(element)[0].nodeName == "INPUT" && $(element).attr("type") == "text") {
                        thisTagName = window.getSelection().anchorNode.tagName;
                    }
                    else {
                        console.log(window.getSelection());
                        thisTagName = window.getSelection().anchorNode.tagName;
                    }
                }
                if (thisTagName == "TEXTAREA" || thisTagName == "INPUT" || (thisTagName=="BODY"&&OsObject == "Chrome")) {
                    result = element.selectionStart;
                }
                else if (thisTagName != null) {
                    if (thisTagName == element.tagName) {
                        if (window.getSelection().anchorNode.textContent == $(element).text()) {
                            result = window.getSelection().anchorOffset;
                        }
                        else {
                            var currentIndex = window.getSelection().anchorOffset;
                            var txt = "";
                            var txtoo = window.getSelection().anchorNode.previousSibling;
                            while (txtoo != null) {
                                txt += txtoo.textContent;
                                txtoo = txtoo.previousSibling;
                            }
                            result = txt.length + currentIndex;
                        }
                    }
                    else {
                        var currentIndex = window.getSelection().anchorOffset;
                        var txt = "";
                        var txtoo = window.getSelection().anchorNode.parentElement.previousSibling;
                        while (txtoo != null) {
                            txt += txtoo.textContent;
                            txtoo = txtoo.previousSibling;
                        }
                        result = txt.length + currentIndex;
                    }
                }
                else {
                    return 0;
                }
            } else { //IE
                var rng;
                if ($(element).attr("tagName") == "TEXTAREA" || ($(element).attr("tagName") == "INPUT" && $(element).attr("type") == "text") || ($(element).attr("tagName") == "DIV" && $(element).attr("contenteditable") == "true")) {
                    element.focus();
                    rng = document.selection.createRange();
                    rng.moveStart(‘character‘, -element.innerText.length);
                    var text = rng.text;
                    for (var i = 0; i < element.innerText.length; i++) {
                        if (element.innerText.substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) {
                            result = i + 1;
                        }
                    }
                }
                else {
                    return 0;
                }
            }
            return result;
        }
        function getValue(element) {
            var pos = getPosition(element);
            document.getElementById("pnum").value = pos;
        }

    </script>
    <style type="text/css">
        #Div1, #Div2
        {
            width: 500px;
            height: 100px;
            border: solid 1px black;
        }
    </style>
</head>
<body>
    <input id="pnum" type="text" value="Hello,wellcome to test! 你好,欢迎测试!" onmouseup="getValue(this)"style="display: block" />

    <textarea cols="60" rows="10" onkeyup="getValue(this)" onmouseup="getValue(this)">Hello,wellcome to test! 你好,欢迎测试! 注意源代码开闭合标记之间不能换行,否则统计错误!</textarea>

    <div id="Div1" onclick="getValue(this);" onkeyup="getValue(this);" contenteditable="true">一二三<span>四五</span>六七八<span>九零</span> 注意源代码开闭合标记之间不能换行,否则统计错误!注意div编辑框源码里面是嵌套有其他标签的,可以正常返回正确位置!</div>

    <div id="Div2" onclick="getValue(this);" onkeyup="getValue(this);">一二三四五六<span>七八</span></div>
</body>
</html>
时间: 2024-10-06 20:53:18

js获取编辑框游标的位置的相关文章

JS获取文本框值

一.获取文本框/编辑框/隐藏域框 <script type="text/javascript">function Mycheck(){  var checkstr="获取内容如下:\n";  if (document.form1.文章作者.value != ""){     checkstr+="作者名称:"+document.form1.文章作者.value+"\n";  }  if (doc

js获取单选框里面的值

rt,如果想获取单选框里面的值,该如何获取呢. <script> window.onload = function(){ //通过名字获取 getElementsByName //var obj = document.getElementsByName("fruit"); //通过标签获取 getElementsByTagName var obj = document.getElementsByTagName("input"); for(var i=0;

js获取单选框radio的值

遇到一个js获取radio值的问题,原来根据frm.type.value取到的值在ie下是空值 解决办法:type为每个radio的值 var chkObjs=document.getElementsByName("group");        for(var i=0;i<chkObjs.length;i++){            if(chkObjs[i].checked){                var type = i;                brea

[原]js获取dom元素的实际位置及相对坐标

关键API: Element.getBoundingClientRect() mdn:https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect 用法: var rect = element.getBoundingClientRect(); console.log(rect.top, rect.right, rect.bottom, rect.left); 获取相对位置: var bodyRect

js获取页面窗口大小以及滚动条位置

function getPageScroll() {         var xScroll, yScroll;         if (self.pageYOffset) {             yScroll = self.pageYOffset;             xScroll = self.pageXOffset;         } else if (document.documentElement && document.documentElement.scroll

JS获取select框的值

var obj = document.getElementsByName('vipActs'); var val = ""; for (var i = 0; i < obj.length; i++) { if(obj[i].checked==true){ val = val + obj[i].value+","; } } //vipActs为复选框的name值

javascript设置input编辑框光标的位置

function set_text_value_position(obj, spos){ var tobj = document.getElementById(obj); if(spos<0) spos = tobj.value.length; if(tobj.setSelectionRange){ //兼容火狐,谷歌 setTimeout(function(){ tobj.setSelectionRange(spos, spos); tobj.focus();} ,0); }else if(t

JS获取单选框checked的value方法

var genderValue=0; var obj = document.getElementsByTagName("input"); document.getElementById('gender').onclick=function(){ for(var i=0; i<obj.length; i ++){ if(obj[i].checked && genderValue!=obj[i].value){ genderValue=obj[i].value; //

Js获取单选框radio的几种方法

首先,编写HTML如下:   <form id="form1">         <table  border="0">              <tr>                 <td>年龄段:</td>                 <td>                     <input type="radio" name="age&q