演示
我编写了一个按预期运行的函数。可以在这里找到一个非常详细的演示面板:Fiddle:http://jsfiddle.net/56Rep/5/
演示中的界面一目了然。
问题中要求的功能将在我的函数中实现如下:
var pixelPosition = getTextBoundingRect(input, 6)
函数依赖
更新:函数是纯 JavaScript,不依赖于任何插件或框架!
该函数假定存在getBoundingClientRect 方法。文本范围在受支持时使用。否则,使用我的功能逻辑来实现功能。
函数逻辑
代码本身包含几个cmets。这部分更详细。
- 创建了一个临时
<div> 容器。
- 1 - 3
<span> 元素被创建。每个 span 包含输入值的一部分(偏移 0 到 selectionStart、selectionStart 到 selectionEnd、selectionEnd 到字符串结尾,只有第二个 span 有意义)。
- 输入元素中的几个重要样式属性被复制到这些
<div> 和<span> 标记中。仅复制重要的样式属性。例如,color 不会被复制,因为它不会以任何方式影响字符的偏移量。#1
-
<div> 位于文本节点(输入值)的确切位置。考虑到边框和填充,以确保临时 <div> 的位置正确。
- 创建了一个变量,它保存了
div.getBoundingClientRect()的返回值。
- 临时的
<div>被移除,除非参数debug被设置为true。
- 该函数返回
ClientRect 对象。有关此对象的更多信息,请参阅this page。 demo 还显示属性列表:top、left、right、bottom、height 和 width。
#1:getBoundingClientRect()(和一些次要属性)用于确定输入元素的位置。然后加上padding和border width,得到一个文本节点的真实位置。
已知问题
当getComputedStyle为font-family返回错误值时遇到了唯一不一致的情况:当页面未定义font-family属性时,computedStyle返回错误值(即使Firebug也遇到此问题;环境: Linux,Firefox 3.6.23,字体“无衬线”)。
从演示中可以看出,定位有时会稍微偏离(几乎为零,始终小于 1 像素)。
技术限制会阻止脚本在内容被移动时获取文本片段的确切偏移量,例如当输入字段中的第一个可见字符不等于第一个值的字符时。
代码
// @author Rob W http://stackoverflow.com/users/938089/rob-w
// @name getTextBoundingRect
// @param input Required HTMLElement with `value` attribute
// @param selectionStart Optional number: Start offset. Default 0
// @param selectionEnd Optional number: End offset. Default selectionStart
// @param debug Optional boolean. If true, the created test layer
// will not be removed.
function getTextBoundingRect(input, selectionStart, selectionEnd, debug) {
// Basic parameter validation
if(!input || !('value' in input)) return input;
if(typeof selectionStart == "string") selectionStart = parseFloat(selectionStart);
if(typeof selectionStart != "number" || isNaN(selectionStart)) {
selectionStart = 0;
}
if(selectionStart < 0) selectionStart = 0;
else selectionStart = Math.min(input.value.length, selectionStart);
if(typeof selectionEnd == "string") selectionEnd = parseFloat(selectionEnd);
if(typeof selectionEnd != "number" || isNaN(selectionEnd) || selectionEnd < selectionStart) {
selectionEnd = selectionStart;
}
if (selectionEnd < 0) selectionEnd = 0;
else selectionEnd = Math.min(input.value.length, selectionEnd);
// If available (thus IE), use the createTextRange method
if (typeof input.createTextRange == "function") {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', selectionStart);
range.moveEnd('character', selectionEnd - selectionStart);
return range.getBoundingClientRect();
}
// createTextRange is not supported, create a fake text range
var offset = getInputOffset(),
topPos = offset.top,
leftPos = offset.left,
width = getInputCSS('width', true),
height = getInputCSS('height', true);
// Styles to simulate a node in an input field
var cssDefaultStyles = "white-space:pre;padding:0;margin:0;",
listOfModifiers = ['direction', 'font-family', 'font-size', 'font-size-adjust', 'font-variant', 'font-weight', 'font-style', 'letter-spacing', 'line-height', 'text-align', 'text-indent', 'text-transform', 'word-wrap', 'word-spacing'];
topPos += getInputCSS('padding-top', true);
topPos += getInputCSS('border-top-width', true);
leftPos += getInputCSS('padding-left', true);
leftPos += getInputCSS('border-left-width', true);
leftPos += 1; //Seems to be necessary
for (var i=0; i<listOfModifiers.length; i++) {
var property = listOfModifiers[i];
cssDefaultStyles += property + ':' + getInputCSS(property) +';';
}
// End of CSS variable checks
var text = input.value,
textLen = text.length,
fakeClone = document.createElement("div");
if(selectionStart > 0) appendPart(0, selectionStart);
var fakeRange = appendPart(selectionStart, selectionEnd);
if(textLen > selectionEnd) appendPart(selectionEnd, textLen);
// Styles to inherit the font styles of the element
fakeClone.style.cssText = cssDefaultStyles;
// Styles to position the text node at the desired position
fakeClone.style.position = "absolute";
fakeClone.style.top = topPos + "px";
fakeClone.style.left = leftPos + "px";
fakeClone.style.width = width + "px";
fakeClone.style.height = height + "px";
document.body.appendChild(fakeClone);
var returnValue = fakeRange.getBoundingClientRect(); //Get rect
if (!debug) fakeClone.parentNode.removeChild(fakeClone); //Remove temp
return returnValue;
// Local functions for readability of the previous code
function appendPart(start, end){
var span = document.createElement("span");
span.style.cssText = cssDefaultStyles; //Force styles to prevent unexpected results
span.textContent = text.substring(start, end);
fakeClone.appendChild(span);
return span;
}
// Computing offset position
function getInputOffset(){
var body = document.body,
win = document.defaultView,
docElem = document.documentElement,
box = document.createElement('div');
box.style.paddingLeft = box.style.width = "1px";
body.appendChild(box);
var isBoxModel = box.offsetWidth == 2;
body.removeChild(box);
box = input.getBoundingClientRect();
var clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || isBoxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || isBoxModel && docElem.scrollLeft || body.scrollLeft;
return {
top : box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft};
}
function getInputCSS(prop, isnumber){
var val = document.defaultView.getComputedStyle(input, null).getPropertyValue(prop);
return isnumber ? parseFloat(val) : val;
}
}