所以,我有一个input
,我希望它调整它的内容width
。现在,我用这样的代码:如何获得HTML输入内文本的准确宽度?
var adjustWidthToContent = function()
{
\t var inputLength = $(this).val().length;
\t // the minimum 1em width allows to start typing when the input is empty
\t $(this).width(Math.max(1, inputLength*0.7) + "em");
};
$("input").on("input",adjustWidthToContent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type='text' />
该工程确定为桌面,但我想使这个更准确的(0.7系数是“哈克”之一,计算实际宽度的那个对于不同的符号明显不同)。尝试输入多个符号:您会发现差距在增大。解决这个问题对于移动界面特别有用,我不希望任何额外的空间被input
元素的空白部分占据。
显然,我需要使用与inputLength
不同的东西。我如何获得input
中文本的“实际”宽度?
PS这里是我使用的基础上,建议:
$.fn.textWidth = function() {
\t if (!$.fn.textWidth.fakeEl)
\t \t $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
\t $.fn.textWidth.fakeEl.text(this.val() || this.text()).css('font', this.css('font'));
\t return $.fn.textWidth.fakeEl.width();
};
var adjustWidthToContent = function()
{
\t var textWidth = jQuery(this).textWidth();
\t var defaultWidth = 20;
\t $(this).width((textWidth || defaultWidth) + 'px');
};
$("input").on("input",adjustWidthToContent).trigger("input");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type='text' />
PPS这确实需要一些阐述了adjustWidthToContent
是适用的有这么几种文本字段,虽然。
试试这个http://stackoverflow.com/questions/4663716/resize-input-to-fit-its-content – Passersby
一个字:** monospace **。 – zer00ne