我花了永远寻找,但也许你想在我的答案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添加标记链接。 –