Calculate text width with JavaScript

前端 未结 24 1620
陌清茗
陌清茗 2020-11-21 05:08

I\'d like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?

If it\'s not built-in, my only idea is t

24条回答
  •  天涯浪人
    2020-11-21 05:31

    I guess this is prety similar to Depak entry, but is based on the work of Louis Lazaris published at an article in impressivewebs page

    (function($){
    
            $.fn.autofit = function() {             
    
                var hiddenDiv = $(document.createElement('div')),
                content = null;
    
                hiddenDiv.css('display','none');
    
                $('body').append(hiddenDiv);
    
                $(this).bind('fit keyup keydown blur update focus',function () {
                    content = $(this).val();
    
                    content = content.replace(/\n/g, '
    '); hiddenDiv.html(content); $(this).css('width', hiddenDiv.width()); }); return this; }; })(jQuery);

    The fit event is used to execute the function call inmediatly after the function is asociated to the control.

    e.g.: $('input').autofit().trigger("fit");

提交回复
热议问题