jQuery 计算文本宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1582534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating text width
提问by Dom
I'm trying to calculate text width using jQuery. I'm not sure what, but I am definitely doing something wrong.
我正在尝试使用 jQuery 计算文本宽度。我不确定是什么,但我肯定做错了什么。
So, here is the code:
所以,这里是代码:
var c = $('.calltoaction');
var cTxt = c.text();
var cWidth = cTxt.outerWidth();
c.css('width' , cWidth);
回答by Rune Kaagaard
This worked better for me:
这对我来说效果更好:
$.fn.textWidth = function(){
var html_org = $(this).html();
var html_calc = '<span>' + html_org + '</span>';
$(this).html(html_calc);
var width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};
回答by philfreo
Here's a function that's better than others posted because
这是一个比其他人发布的更好的功能,因为
- it's shorter
- it works when passing an
<input>
,<span>
, or"string"
. - it's faster for frequent uses because it reuses an existing DOM element.
- 它更短
- 它在传递
<input>
,<span>
, 或时起作用"string"
。 - 频繁使用它更快,因为它重用了现有的 DOM 元素。
Demo: http://jsfiddle.net/philfreo/MqM76/
演示:http: //jsfiddle.net/philfreo/MqM76/
// Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com>
$.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();
};
回答by bevacqua
$.fn.textWidth = function(){
var self = $(this),
children = self.children(),
calculator = $('<span style="display: inline-block;" />'),
width;
children.wrap(calculator);
width = children.parent().width(); // parent = the calculator wrapper
children.unwrap();
return width;
};
Basically an improvement over Rune's, that doesn't use .html
so lightly
基本结束了符文的改善,不使用.html
如此轻视
回答by edsioufi
The textWidth
functions provided in the answers and that accept a string
as an argument will not account for leading and trailing white spaces (those are not rendered in the dummy container). Also, they will not work if the text contains any html markup (a sub-string <br>
won't produce any output and
will return the length of one space).
textWidth
答案中提供的函数以及接受 astring
作为参数的函数将不考虑前导和尾随空格(那些不在虚拟容器中呈现)。此外,如果文本包含任何 html 标记,它们将不起作用(子字符串<br>
不会产生任何输出并
返回一个空格的长度)。
This is only a problem for the textWidth
functions which accept a string
, because if a DOM element is given, and .html()
is called upon the element, then there is probably no need to fix this for such use case.
这只是textWidth
接受 a的函数的问题string
,因为如果给定了一个 DOM 元素,并.html()
在该元素上调用,那么对于这种用例可能不需要修复它。
But if, for example, you are calculating the width of the text to dynamically modify the width of an text input
element as the user types (my current use case), you'll probably want to replace leading and trailing spaces with
and encode the string to html.
但是,例如,如果您正在计算文本的宽度input
以在用户键入时动态修改文本元素的宽度(我当前的用例),您可能希望用
字符串替换前导和尾随空格并对其进行编码到 html。
I used philfreo's solution so here is a version of it that fixes this (with comments on additions):
我使用了 philfreo 的解决方案,所以这里有一个解决这个问题的版本(对添加的评论):
$.fn.textWidth = function(text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').appendTo(document.body);
var htmlText = text || this.val() || this.text();
htmlText = $.fn.textWidth.fakeEl.text(htmlText).html(); //encode to Html
htmlText = htmlText.replace(/\s/g, " "); //replace trailing and leading spaces
$.fn.textWidth.fakeEl.html(htmlText).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
回答by brianreavis
jQuery's width functions can be a bit shady when trying to determine the text width due to inconsistent box models. The sure way would be to inject div inside your element to determine the actual text width:
由于框模型不一致,在尝试确定文本宽度时,jQuery 的宽度函数可能有点可疑。确定的方法是在元素中注入 div 以确定实际的文本宽度:
$.fn.textWidth = function(){
var sensor = $('<div />').css({margin: 0, padding: 0});
$(this).append(sensor);
var width = sensor.width();
sensor.remove();
return width;
};
To use this mini plugin, simply:
要使用这个迷你插件,只需:
$('.calltoaction').textWidth();
回答by Vince Spicer
I found this solution works well and it inherits the origin font before sizing:
我发现这个解决方案效果很好,它在调整大小之前继承了原始字体:
$.fn.textWidth = function(text){
var org = $(this)
var html = $('<span style="postion:absolute;width:auto;left:-9999px">' + (text || org.html()) + '</span>');
if (!text) {
html.css("font-family", org.css("font-family"));
html.css("font-size", org.css("font-size"));
}
$('body').append(html);
var width = html.width();
html.remove();
return width;
}
回答by chmurson
Neither Rune's nor Brain's was working for me in case when the element that was holding the text had fixed width. I did something similar to Okamera. It uses less selectors.
如果保存文本的元素具有固定宽度,Rune 和 Brain 都不适合我。我做了一些类似于 Okamera 的事情。它使用较少的选择器。
EDIT:
It won't probably work for elements that uses relative font-size
, as following code inserts htmlCalc
element into body
thus looses the information about parents relation.
编辑:它可能不适用于使用 relative 的元素font-size
,因为以下代码将htmlCalc
元素插入其中,body
从而丢失了有关父关系的信息。
$.fn.textWidth = function() {
var htmlCalc = $('<span>' + this.html() + '</span>');
htmlCalc.css('font-size', this.css('font-size'))
.hide()
.prependTo('body');
var width = htmlCalc.width();
htmlCalc.remove();
return width;
};
回答by okamera
If your trying to do this with text in a select box or if those two arent working try this one instead:
如果您尝试使用选择框中的文本执行此操作,或者如果这两个不起作用,请尝试使用以下方法:
$.fn.textWidth = function(){
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
or
或者
function textWidth(text){
var calc = '<span style="display:none">' + text + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
if you want to grab the text first
如果你想先抓取文本
回答by Juraj Blahunka
the thing, you are doing wrong, that you are calling a method on cTxt, which is a simple string and not a jQuery object. cTxt is really the contained text.
事情,你做错了,你正在调用 cTxt 上的一个方法,它是一个简单的字符串,而不是一个 jQuery 对象。cTxt 实际上是包含的文本。
回答by 309designer
Slight change to Nico's, since .children() will return an empty set if we're referencing a text element like an h1or p. So we'll use .contents() instead, and use thisinstead of $(this) since we're creating a method on a jQuery object.
对 Nico 的稍微改变,因为如果我们引用像h1或p这样的文本元素, .children() 将返回一个空集。所以我们将使用 .contents() 代替,并使用this代替 $(this) 因为我们正在一个 jQuery 对象上创建一个方法。
$.fn.textWidth = function(){
var contents = this.contents(),
wrapper = '<span style="display: inline-block;" />',
width = '';
contents.wrapAll(wrapper);
width = contents.parent().width(); // parent is now the wrapper
contents.unwrap();
return width;
};