使用JavaScript计算文字宽度
时间:2020-03-06 14:34:18 来源:igfitidea点击:
我想使用JavaScript计算字符串的宽度。是否可以不必使用等宽字体?
如果不是内置的,我唯一的想法就是为每个字符创建一个宽度表,但这是非常不合理的,特别是支持Unicode和不同类型的大小(以及与此相关的所有浏览器)。
解决方案
创建具有以下样式的DIV。在JavaScript中,设置要测量的字体大小和属性,将字符串放入DIV中,然后读取DIV的当前宽度和高度。它将拉伸以适合内容,并且大小将在字符串呈现大小的几个像素之内。
var fontSize = 12; var test = document.getElementById("Test"); test.style.fontSize = fontSize; var height = (test.clientHeight + 1) + "px"; var width = (test.clientWidth + 1) + "px" console.log(height, width);
#Test { position: absolute; visibility: hidden; height: auto; width: auto; white-space: nowrap; /* Thanks to Herb Caudill comment */ }
<div id="Test"> abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ </div>
<span id="text">Text</span> <script> var textWidth = document.getElementById("text").offsetWidth; </script>
只要<span>标记没有应用其他样式,它就应该起作用。
offsetWidth将包括所有边框的宽度,水平填充,垂直滚动条宽度等。
ExtJS javascript库具有一个称为Ext.util.TextMetrics的出色类,该类"为文本块提供精确的像素测量,以便我们可以精确确定给定的文本块的高度和宽度(以像素为单位)"。我们可以直接使用它,也可以查看其源代码以查看其完成方式。
http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html
jQuery的:
(function($) { $.textMetrics = function(el) { var h = 0, w = 0; var div = document.createElement('div'); document.body.appendChild(div); $(div).css({ position: 'absolute', left: -1000, top: -1000, display: 'none' }); $(div).html($(el).html()); var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing']; $(styles).each(function() { var s = this.toString(); $(div).css(s, $(el).css(s)); }); h = $(div).outerHeight(); w = $(div).outerWidth(); $(div).remove(); var ret = { height: h, width: w }; return ret; } })(jQuery);
下面的代码片段"计算" span-tag的宽度,如果它太长,则在其后面添加" ...",并减小文本长度,直到适合其父级为止(或者尝试了多次)一千次)
的CSS
div.places { width : 100px; } div.places span { white-space:nowrap; overflow:hidden; }
的HTML
<div class="places"> <span>This is my house</span> </div> <div class="places"> <span>And my house are your house</span> </div> <div class="places"> <span>This placename is most certainly too wide to fit</span> </div>
JavaScript(使用jQuery)
// loops elements classed "places" and checks if their child "span" is too long to fit $(".places").each(function (index, item) { var obj = $(item).find("span"); if (obj.length) { var placename = $(obj).text(); if ($(obj).width() > $(item).width() && placename.trim().length > 0) { var limit = 0; do { limit++; placename = placename.substring(0, placename.length - 1); $(obj).text(placename + "..."); } while ($(obj).width() > $(item).width() && limit < 1000) } } });
这对我有用...
// Handy JavaScript to measure the size taken to render the supplied text; // you can supply additional style information too if you have it. function measureText(pText, pFontSize, pStyle) { var lDiv = document.createElement('div'); document.body.appendChild(lDiv); if (pStyle != null) { lDiv.style = pStyle; } lDiv.style.fontSize = "" + pFontSize + "px"; lDiv.style.position = "absolute"; lDiv.style.left = -1000; lDiv.style.top = -1000; lDiv.innerHTML = pText; var lResult = { width: lDiv.clientWidth, height: lDiv.clientHeight }; document.body.removeChild(lDiv); lDiv = null; return lResult; }