获取输入元素的光标或文本位置(以像素为单位) [英] Get cursor or text position in pixels for input element
问题描述
IE 允许我在输入元素中创建文本范围,然后我可以调用 getBoundingClientRect()
并获取特定字符或光标/插入符号的像素位置.有没有办法在其他浏览器中获取某个字符的位置以像素为单位?
IE allows me to create a text range in an input element, upon which I can call getBoundingClientRect()
and get the position in pixels of a certain character or the cursor/caret. Is there any way of getting the position of a certain character in pixels in other browsers?
var input = $("#myInput")[0];
var pixelPosition = null;
if (input.createTextRange)
{
var range = input.createTextRange();
range.moveStart("character", 6);
pixelPosition = range.getBoundingClientRect();
}
else
{
// Is there any way to create a range on an input's value?
}
我正在使用 jQuery,但我怀疑它能否解决我的情况.我希望有一个纯 JavaScript 解决方案(如果有),但欢迎提供 jQuery 答案.
I'm using jQuery, but I doubt it will be able to address my situation. I expect a pure JavaScript solution, if any, but jQuery answers are welcome.
推荐答案
我最终从绝对定位的跨度中创建了一个隐藏的模拟输入,其样式与输入相似.我将该跨度的文本设置为输入的值,直到我要查找其位置的字符.我在输入之前插入跨度并得到它的偏移量:
I ended up creating a hidden mock input out of a span positioned absolutely and styled similarly to the input. I set the text of that span to the value of the input up to the character whose position I want to find. I insert the span before the input and get it's offset:
function getInputTextPosition(input, charOffset)
{
var pixelPosition = null;
if (input.createTextRange)
{
var range = input.createTextRange();
range.moveStart("character", charOffset);
pixelPosition = range.getBoundingClientRect();
}
else
{
var text = input.value.substr(0, charOffset).replace(/ $/, "xa0");
var sizer = $("#sizer").insertBefore(input).text(text);
pixelPosition = sizer.offset();
pixelPosition.left += sizer.width();
if (!text) sizer.text("."); // for computing height. An empty span returns 0
pixelPosition.bottom = pixelPosition.top + sizer.height();
}
return pixelPosition
}
我的 sizer 跨度的 css:
The css for my sizer span:
#sizer
{
position: absolute;
display: inline-block;
visibility: hidden;
margin: 3px; /* simulate padding and border without affecting height and width */
font-family: "segoe ui", Verdana, Arial, Sans-Serif;
font-size: 12px;
}
这篇关于获取输入元素的光标或文本位置(以像素为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!