Calculating text width
I'm trying to calculate text width using jQuery. I'm not sure what, but I am definitely doing something wrong.
So, here i开发者_如何学Pythons the code:
var c = $('.calltoaction');
var cTxt = c.text();
var cWidth = cTxt.outerWidth();
c.css('width' , cWidth);
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;
};
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.
Demo: 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();
};
My solution
$.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
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).
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.
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.
I used philfreo's solution so here is a version of it that fixes this (with comments on additions):
$.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();
};
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:
$.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();
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;
}
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.
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.
$.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;
};
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
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.
Slight change to Nico's, since .children() will return an empty set if we're referencing a text element like an h1 or p. So we'll use .contents() instead, and use this instead of $(this) since we're creating a method on a jQuery object.
$.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;
};
after chasing a ghost for two days, trying to figure out why the width of a text was incorrect, i realized it was because of white spaces in the text string that would stop the width calculation.
so, another tip is to check if the whitespaces are causing problems. use
non-breaking space and see if that fixes it up.
the other functions people suggested work well too, but it was the whitespaces causing trouble.
If you are trying to determine the width of a mix of text nodes and elements inside a given element, you need to wrap all the contents with wrapInner(), calculate the width, and then unwrap the contents.
*Note: You will also need to extend jQuery to add an unwrapInner() function since it is not provided by default.
$.fn.extend({
unwrapInner: function(selector) {
return this.each(function() {
var t = this,
c = $(t).children(selector);
if (c.length === 1) {
c.contents().appendTo(t);
c.remove();
}
});
},
textWidth: function() {
var self = $(this);
$(this).wrapInner('<span id="text-width-calc"></span>');
var width = $(this).find('#text-width-calc').width();
$(this).unwrapInner();
return width;
}
});
Expanding on @philfreo's answer:
I've added the ability to check for text-transform
, as things like text-transform: uppercase
usually tend to make the text wider.
$.fn.textWidth = function (text, font, transform) {
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'))
.css('text-transform', transform || this.css('text-transform'));
return $.fn.textWidth.fakeEl.width();
};
var calc = '<span style="display:none; margin:0 0 0 -999px">' + $('.move').text() + '</span>';
Call getColumnWidth() to get the with of the text. This works perfectly fine.
someFile.css
.columnClass {
font-family: Verdana;
font-size: 11px;
font-weight: normal;
}
function getColumnWidth(columnClass,text) {
tempSpan = $('<span id="tempColumnWidth" class="'+columnClass+'" style="display:none">' + text + '</span>')
.appendTo($('body'));
columnWidth = tempSpan.width();
tempSpan.remove();
return columnWidth;
}
Note:- If you want inline .css pass the font-details in style only.
I modified Nico's code to work for my needs.
$.fn.textWidth = function(){
var self = $(this),
children = self.contents(),
calculator = $('<span style="white-space:nowrap;" />'),
width;
children.wrap(calculator);
width = children.parent().width(); // parent = the calculator wrapper
children.unwrap();
return width;
};
I'm using .contents() as .children() does not return text nodes which I needed. I also found that the returned width was impacted by the viewport width which was causing wrapping so I'm using white-space:nowrap; to get the correct width regardless of viewport width.
$.fn.textWidth = function(){
var w = $('body').append($('<span stlye="display:none;" id="textWidth"/>')).find('#textWidth').html($(this).html()[0]).width();
$('#textWidth').remove();
console.log(w);
return w;
};
almost a one liner. Gives you the with of the first character
I could not get any of the solutions listed to work 100%, so came up with this hybrid, based on ideas from @chmurson (which was in turn based on @Okamera) and also from @philfreo:
(function ($)
{
var calc;
$.fn.textWidth = function ()
{
// Only create the dummy element once
calc = calc || $('<span>').css('font', this.css('font')).css({'font-size': this.css('font-size'), display: 'none', 'white-space': 'nowrap' }).appendTo('body');
var width = calc.html(this.html()).width();
// Empty out the content until next time - not needed, but cleaner
calc.empty();
return width;
};
})(jQuery);
Notes:
this
inside a jQuery extension method is already a jQuery object, so no need for all the extra$(this)
that many examples have.- It only adds the dummy element to the body once, and reuses it.
- You should also specify
white-space: nowrap
, just to ensure that it measures it as a single line (and not line wrap based on other page styling). - I could not get this to work using
font
alone and had to explicitly copyfont-size
as well. Not sure why yet (still investigating). - This does not support input fields that way
@philfreo
does.
Sometimes you also need to measure additionally height and not only text, but also HTML width. I took @philfreo answer and made it more flexbile and useful:
function htmlDimensions(html, font) {
if (!htmlDimensions.dummyEl) {
htmlDimensions.dummyEl = $('<div>').hide().appendTo(document.body);
}
htmlDimensions.dummyEl.html(html).css('font', font);
return {
height: htmlDimensions.dummyEl.height(),
width: htmlDimensions.dummyEl.width()
};
}
text width can be different for different parents, for example if u add a text into h1 tag it will be wider than div or label, so my solution like this:
<h1 id="header1">
</h1>
alert(calcTextWidth("bir iki", $("#header1")));
function calcTextWidth(text, parentElem){
var Elem = $("<label></label>").css("display", "none").text(text);
parentElem.append(Elem);
var width = Elem.width();
Elem.remove();
return width;
}
I had trouble with solutions like @rune-kaagaard's for large amounts of text. I discovered this:
$.fn.textWidth = function() {
var width = 0;
var calc = '<span style="display: block; width: 100%; overflow-y: scroll; white-space: nowrap;" class="textwidth"><span>' + $(this).html() + '</span></span>';
$('body').append(calc);
var last = $('body').find('span.textwidth:last');
if (last) {
var lastcontent = last.find('span');
width = lastcontent.width();
last.remove();
}
return width;
};
JSFiddle GitHub
If the field is a fixed-width input or contenteditable div, you can get the horizontal scroll width as scrollWidth
$("input").on("input", function() {
var width = el[0].scrollWidth;
console.log(width);
});
精彩评论