Я пытаюсь установить поле ввода, чтобы убедиться, что пользователь может видеть общую длину поля ввода.
например
<input size='60' type='text'/>
Я хочу, чтобы пользователь мог видеть всего 60 символов одновременно, а не видеть, что общая длина усечена примерно до 50.
Я не могу указать ширину поля ввода, потому что нет способа узнать, какая ширина будет (может быть короткой или длинной и динамичной).
Может ли кто-нибудь понять, как это сделать? Благодарю!
Несколько неуклюжий подход, который выполняет итерации по каждому input
элементу, создает div
, копирует CSS input
в созданный div
, применяет float
(чтобы разрешить его ширину определяться его содержимым), а затем присваивает эту ширину input
(и удаляет созданный элемент):
$('input[type="text"]').css('width', function (){
// gets the applied style as it appears once rendered in the page:
var styles = window.getComputedStyle(this, null),
// temporary element:
tmp = document.createElement('div');
// creates a textNode child for the div, containing the value of the input:
tmp.appendChild(document.createTextNode(this.value));
// sets the style attribute of the div to those styles of the input
// (note that 'tmp.style = styles['cssText']' did not work, sadly):
tmp.setAttribute('style', styles['cssText']);
// floating, so the width is determined by the content, not the parent-width:
tmp.style.float = 'left';
// appends the div to the body:
document.body.appendChild(tmp);
// gets the rendered width of the div and stores it:
var w = window.getComputedStyle(tmp, null).width;
// removes the div, since it no longer required:
tmp.parentNode.removeChild(tmp);
// returns the width, to set the width of the input element:
return w;
});
Если вы используете шрифт Monospaced (фиксированная ширина на символ), ширина входного окна должна вместить до 60 символов. Протестировано в IE10, Firefox 22 и Chrome 30.0.1599.69
Пример использования моноширинного шрифта для исправления:
<input size='60' maxlength='60' style="font-family: 'Courier New', Courier, monospace;" type='text' value='123456789012345678901234567890123456789012345678901234567890'/>
Если вы ищете динамическую ширину ввода, вы можете использовать обработчик событий:
$("input").keyup(function(){
$(this).width($("input").val().length * w); // w = width of a single char (if monospace), otherwise max char width
});