我花了永遠尋找,但也許你想在我的答案here類似。
使用此代碼,你可以找到文本的寬度並從,計算你的字符串將是寬度。
function charSizes(numChars, cssFont) {
var span = document.createElement('span'),
text = document.createTextNode(''),
uia, i, j;
span.appendChild(text);
if (cssFont) span.style.font = cssFont;
span.style.padding = span.style.margin = 'none';
document.body.appendChild(span);
numChars = (numChars || 255);
uia = new Uint32Array(numChars * 2);
for (j = i = 0; i < numChars; j = 2 * ++i) {
text.data = String.fromCharCode(i);
uia[j] = span.offsetWidth;
uia[j + 1] = span.offsetHeight;
}
// free memory
document.body.removeChild(span);
span = text = numChars = cssFont = null;
// output lookup function
return function (c) {
var i = c.charCodeAt(0) * 2;
return {
width: uia[i],
height: uia[i + 1]
};
};
}
var defaultFont = charSizes(0xFF); // match the style of the text in your marquee
// using the second parameter if necessary
現在
var str = 'foobar', i, len = 0;
for (i = 0; i < str.length; ++i) {
len += defaultFont(str[i]).width;
}
len; // 36 pixels on this page
如果我們有關於您的標記的更多信息,你也許可以直接測量你的DOM的#text節點。
你能分享你的HTML標記,以便我們可以看到如何實現選取框嗎? – Shiva
@Shiva添加標記鏈接。 –