日期:2014-05-16  浏览次数:20412 次

Jquery 获得输入div光标的位置
在网上找了个IE里 JavaScript 的实现方法 ,但是 火狐谷歌等浏览器不行啊,我是想 Jquery 能不能实现呢?大家帮忙看一下,下面是 JavaScript 的实现方法:
HTML code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  
<html>  
    <head>  
        <title> new document </title>  
    </head>  
    <body>  
        <div contentEditable="true" style="height:50px; border:2px solid red;"></div>  
        光标前的字符:<span id="selection"></span>  
        <script language="javascript">  
        <!--  
            var cursor = 0;// 光标位置  
  
            document.onselectionchange = function() {  
                var range = document.selection.createRange();  
                var srcele = range.parentElement();  
                var copy = document.body.createTextRange();  
                copy.moveToElementText(srcele);  
  
                for (cursor = 0; copy.compareEndPoints("StartToStart", range) < 0; cursor++) {  
                    copy.moveStart("character", 1);  
                }  
                document.getElementById("selection").innerText = srcele.innerText.substring(cursor - 1, cursor);  
            }  
        //-->  
        </script>  
    </body>  
</html>  



------解决方案--------------------
HTML code

<!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> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>java Test</title> 
</head> 
<style type="text/css"> 
<!-- 
body,div { margin:0; padding:0;} 
--> 
</style> 
<script type="text/javascript" src="js/jquery.js"></script> 

<body> 
<div style="background:#ccc;height:300px;" onclick=""></div> 
<div style="position:relative;"> 
<div style=" position:absolute;left:50px; top:50px;" id="DivID"></div> 
</div> 
<script type="text/javascript"> 
var X = $('#DivID').offset().top; 
var Y = $('#DivID').offset().left; 
document.write(X+"<br />"); 
document.write(Y+"<br />"); 
//获取相对(父元素)位置: 
var C = $('#DivID').position().top; 
var D = $('#DivID').position().left; 
document.write(C+"<br />"); 
document.write(D); 
</script> 
</body> 
</html>