在附加输入旁边拉伸 HTML 输入框?
我在这个网站上使用 jQuery,它有表单输入。我希望当用户输入数据并且空间耗尽时,一个特定字段变得更长(宽度)。
如何计算何时实际上需要使输入 (type="text"
) 更长? 对一种浏览器有效的方法可能无效适用于所有浏览器。
这是无法计算的东西,所以每个人都根据每个浏览器中的试验和错误来进行计算吗?我是否需要诉诸于此并使用 .keyup() 来检查拉伸值价值?..例如..
$(".stretchInput").keyup( function(event) {
var someValueAdjustedByTrialAndError = 30;
var stretchPastLength = someValueAdjustedByTrialAndError;
var stretchBy = 5;
var baseWidth = 100;
if ($(this).val().length > stretchPastLength ) {
$(this).css('width',(baseWidth + ($(this).val().length - stretchPastLength ) * stretchBy ) + 'px');
} else {
$(this).css('width','');
}
});
I'm using jQuery on this site, which has form inputs. I'd like one particular field to get longer (width) as the user enters data and space runs out.
How can I calculate when I ACTUALLY need to make the input (type="text"
) longer? What works for one browser may not work for all browsers.
Is this something that can't be calculated, so everybody does it based on trial and error within each browser? Will I need to resort to this and tweak stretch values with a .keyup() that checks the value?.. EG..
$(".stretchInput").keyup( function(event) {
var someValueAdjustedByTrialAndError = 30;
var stretchPastLength = someValueAdjustedByTrialAndError;
var stretchBy = 5;
var baseWidth = 100;
if ($(this).val().length > stretchPastLength ) {
$(this).css('width',(baseWidth + ($(this).val().length - stretchPastLength ) * stretchBy ) + 'px');
} else {
$(this).css('width','');
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[已更新以检测退格键]
在页面上以及
的
keyup
事件中放置一个隐藏的元素字段,您可以镜像跨度中的输入值。更新输入字段宽度以匹配您的跨度。
Html:
注意输入元素上的
min-width
值,该值是为了防止宽度缩小到某个值以下。jQuery:
[UPDATED to detect backspace]
Place a hidden
<span>
element on the page, and within thekeyup
event of your<input>
field you can mirror the input value in your span. Update the input field width to match your span.Html:
Note the
min-width
value on the input element that is there to prevent the width from shrinking below a certain value.jQuery:
TextAreas 解决方案
描述
这听起来像是您想要一个像 Facebook 上一样的自动增长的文本区域。如果是这样
为什么要重新发明轮子?
我鼓励您使用精彩的
Eternity jQuery 插件
。更多信息
文本输入解决方案
这是我针对
input
元素的解决方案。问题是每个字体上的字符宽度并不是均匀。
如果你选择courier作为字体,就可以让它变得完美。
示例
Html
jQuery
查看我的 jsFiddle
Solution for TextAreas
Description
This sounds like you want a auto growing textarea like on facebook. If so
why reinvent the wheel ?
I encorage you to use the wonderful
Elasting jQuery Plugin
.More Information
Solution for Text Inputs
Here my solution for
input
elements.The problem is that the width of a char is not evenly on every font.
If you choose courier as the font, you can make it perfect.
Sample
Html
jQuery
Check out my jsFiddle