gpt4 book ai didi

javascript - 动态创建的文本输入不会调整宽度

转载 作者:太空宇宙 更新时间:2023-11-04 14:27:53 25 4
gpt4 key购买 nike

一个简单的问题,我正在尝试根据用户输入自动调整输入文本字段的大小,但动态创建的输入文本字段存在一些问题,而其他的则正常工作。

这是javascript,我正在使用:

<script>
(function($){
$.fn.autoGrowInput = function(o) {

o = $.extend({
maxWidth: 1000,
minWidth: 0,
comfortZone: 70
}, o);

this.filter('input:text').each(function(){

var minWidth = o.minWidth || $(this).width(),
val = '',
input = $(this),
testSubject = $('<tester/>').css({
position: 'absolute',
top: -9999,
left: -9999,
width: 'auto',
fontSize: input.css('fontSize'),
fontFamily: input.css('fontFamily'),
fontWeight: input.css('fontWeight'),
letterSpacing: input.css('letterSpacing'),
whiteSpace: 'nowrap'
}),
check = function() {

if (val === (val = input.val())) {return;}

// Enter new content into testSubject
var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,'&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
testSubject.html(escaped);

// Calculate new width + whether to change
var testerWidth = testSubject.width(),
newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
currentWidth = input.width(),
isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
|| (newWidth > minWidth && newWidth < o.maxWidth);

// Animate width
if (isValidWidthChange) {
input.width(newWidth);
}

};

testSubject.insertAfter(input);

$(this).bind('keyup keydown blur update', check);

});

return this;

};

})(jQuery);

$('input').autoGrowInput();

</script>

这就是我创建文本输入字段的方式:

                var tracktitleinput = document.createElement('input');
tracktitleinput.setAttribute('type', "text");
tracktitleinput.setAttribute('name', "tracktitle");
tracktitleinput.setAttribute("required", true);
tracktitleinput.setAttribute("placeholder",
"Required Field");
tracktitleinput.setAttribute("class", "required");

它确实与这些完美搭配:

<input type="text" id="releasename" name="releasename" required="true" placeholder="Required Field" />

最佳答案

当您创建新的输入时,您需要为这些元素调用 autoGrowInput() 函数:

var $newInput = $('<input/>', {
type : 'text',
name : 'tracktitle',
required : 'true',
placeholder : 'Required Field',
class : 'required'
}).autoGrowInput();

关于javascript - 动态创建的文本输入不会调整宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19404301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com