Calculating text width

后端 未结 22 1615
轻奢々
轻奢々 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: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 = '' + $(this).html() + '';
    	$('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

提交回复
热议问题