试试这个solution, developed by Ben Ripkens
CSS:
.textDimensionCalculation {
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap;
}
JS :
var calculateWordDimensions = function(text, classes, escape) {
classes = classes || [];
if (escape === undefined) {
escape = true;
}
classes.push('textDimensionCalculation');
var div = document.createElement('div');
div.setAttribute('class', classes.join(' '));
if (escape) {
$(div).text(text);
} else {
div.innerHTML = text;
}
document.body.appendChild(div);
var dimensions = {
width : jQuery(div).outerWidth(),
height : jQuery(div).outerHeight()
};
div.parentNode.removeChild(div);
return dimensions;
};
在他的博客,他写道
有了这个小片段的帮助下,我们可以计算出文本这样一直也写:
var dimensions = calculateWordDimensions('42 is the answer!'); <!--obviously a hitchhikers guide fan, lol --->
console.log(dimensions.width);
console.log(dimensions.height);
的alternate [jquery] solution 尺寸菲尔Freo
$.fn.textWidth = function(text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
遇到问题SUG孕育了一个解决方案,因为我不完全清楚你想做什么 - 是根据字符在字符串中的位置定位HTML元素的目标?或者在字符串的那一点插入一些东西? – Toby
@Toby我试图在该位置放置另一个元素,是的。 – Halliom
@RachelGallen链接问题的答案,我将创建一个带有字符串的隐藏div,然后用它来计算字符宽度。 – Halliom