在textarea中查找插入符位置(以像素为单位) [英] Find caret position in textarea in pixels

查看:130
本文介绍了在textarea中查找插入符位置(以像素为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以找到carret在textarea内相对于整个页面的像素的确切位置。例如,如果我键入这是文本到我的文本框中,我想知道从屏幕左上角到carot的像素。

I was wondering if it is possible to find the exact location of the carret inside a textarea in pixels in relation to the entire page. For instance, if I have typed This is text into my text box, I would like to know the pixes from the top left of the screen to the carot.

这将是X:200 Y:100.这是我可以放置一个浮动div。这需要在 javascript 中动态完成。

It would be in the form X: 200 Y: 100. This is so I can position a floating div. This needs to be done dynamically in javascript.

感谢伙伴

推荐答案

这个原始代码至少在IE中起作用。

This "raw code" works at least in IE.

使用代码可以将< TEXTAREA ; 在页面中你想要的,并且< DIV id =db> 即使页面的滚动位置。您可以通过更改 d.style ... 6下的文字数字来修正< DIV> 的位置... 6 -

Using the code you can put your <TEXTAREA> where ever you want in page, and the <DIV id="db"> will follow it. Even despite of the scrolling position of the page. You can fix the position of <DIV> by changing the literal numbers at d.style...6-statements.

<body>
<div id="db" style="position:absolute;left:-20px;top:-20px;border:1px solid red;">V</div>
<br><br><br>
<form id="props">
<textarea id="ta" style="width:200px;height:100px;" onkeyup="moveDiv();"></textarea>
</form>

<script>
<!--
var b=document.body;
var d=document.getElementById('db');
var a=document.getElementById('ta');

function moveDiv(){
    var sel=document.selection;
    var targ=sel.createRange();
    d.style.top=a.offsetTop+a.clientTop-d.clientHeight-6;
    d.style.left=targ.offsetLeft+b.scrollLeft-6;
    return;
}
// -->
</script>
</body>

< DIV> 的位置不完全准确,但在< TEXTAREA> 中使用固定宽度字体时会变得更好。

Positioning of the <DIV> is not quite exact, but gets better when using fixed-width font in <TEXTAREA>.

这篇关于在textarea中查找插入符位置(以像素为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆