尝试让我的输入框 [type='text'] 在页面加载时根据其内容重新调整大小。使用此代码,他们可以有效地调整焦点 的大小。
$(document).ready(function () {
$("input[type='text']").bind('focus', function () {
$(this).attr("size", $(this).val().length );
});
});
我曾尝试为不同的事件(例如“加载”和“就绪”)交换“焦点”,但无济于事。请记住,我正在寻找轻量级和快速的东西,它将在页面加载时将所有输入 [type='text'] 框的大小调整为它们的内容。
解决方案
我最终使用了 Thom's answer 作为解决方案,但我随后意识到我还希望输入框在输入文本时扩展。所以我结合了我之前的内容和 Thom 的回答来提供这两个功能。我还添加了 css 以确保它不会超出页面大小。这是我的最终代码:
HTML
<input type="text" value="resized onload and when typing"/>
jQuery
$(document).ready(function () {
$("input[type='text']" ).each(function( index ) {
$(this).attr("size", $(this).val().length + 5 );
});
$("input[type='text']").bind('keyup', function () {
$(this).attr("size", $(this).val().length + 5);
});
});
CSS
input[type="text"]{ max-width:100%;}
最佳答案
在 dom 就绪时循环遍历它们:
jQuery(document).ready(function($)
{
$("input[type='text']").each(function()
{
$(this).attr("size", $(this).val().length);
});
});
关于javascript - 将输入框调整为内容 onload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30156191/