Calculating text width

后端 未结 22 1326
轻奢々
轻奢々 2020-11-22 03:36

I\'m trying to calculate text width using jQuery. I\'m not sure what, but I am definitely doing something wrong.

So, here is the code:

var c = $(\'.c         


        
相关标签:
22条回答
  • 2020-11-22 04:04

    Here's a function that's better than others posted because

    1. it's shorter
    2. it works when passing an <input>, <span>, or "string".
    3. 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();
    };
    
    0 讨论(0)
  • 2020-11-22 04:04

    i think you should use $('.calltoaction').val;

    also, i would be using id (#) instead of a class for that.. if u have more than one of such classes which how would it handle it?

    0 讨论(0)
  • 2020-11-22 04:05

    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;
    };
    
    0 讨论(0)
  • 2020-11-22 04:05

    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

    0 讨论(0)
提交回复
热议问题