我有以下测量元素宽度的函数:
function distanceToCaret(textElement,caretIndex){
line = findLineViaCaret(textElement,caretIndex);
relativeIndex = caretIndex - line.startIndex;
textToCaret = line.text.substring(0, relativeIndex);
hiddenElement = textElement.clone(); //copies font settings and width
hiddenElement.empty();//clear text
hiddenElement.css("visibility", "hidden");
hiddenElement.css("width", "auto"); //so width can be measured
hiddenElement.css("display", "inline-block"); //so width can be measured
jQuery('body').append(hiddenElement); // height doesn't exist until inserted into document
hiddenElement.text(textToCaret); //add character to get height
width = hiddenElement.width();
hiddenElement.remove();
return width;
}
我称之为:
distanceToCaret = distanceToCaret($(this), thisIndex);
我第一次调用这个函数时它会返回“72”,第二次调用它我得到错误:
TypeError: '72' is not a function (evaluating 'distanceToCaret($(this), thisIndex)')
事实上,如果disctanceToCaret
在我打电话之前完全定义了distanceToCaret = distanceToCaret();
我会收到这个错误。为什么会这样?