Отрегулируйте ширину поля ввода для его ввода - PullRequest
137 голосов
/ 03 августа 2010
<html>
  <head>
  </head>
  <body>
    <input type="text" value="1" style="min-width:1px;" />
  </body>
</html>

Это мой код, и он не работает.Есть ли другой способ в HTML, JavaScript, PHP или CSS установить минимальную ширину?

Мне нужно поле ввода текста с динамически изменяющейся шириной, чтобы поле ввода перемещалось вокруг его содержимого.Каждый вход имеет встроенный отступ 2em, это проблема, и вторая проблема заключается в том, что min-width вообще не работает на входе.

Если я установил ширину больше, чем нужно, чемвся программа грязная, мне нужна ширина 1px, больше только если она нужна.

Ответы [ 24 ]

0 голосов
/ 07 февраля 2017

Основываясь на ответе Майкла, я создал свою собственную версию, используя jQuery. Я думаю, что это более чистая / короткая версия большинства ответов здесь, и похоже, что работа сделана.

Я делаю то же самое, что и большинство людей здесь, используя диапазон для записи входного текста, а затем получая ширину. Затем я устанавливаю ширину при вызове действий keyup и blur.

Вот рабочая кодовая ручка . Этот кодовый блок показывает, как его можно использовать с несколькими полями ввода.

Структура HTML:

<input type="text" class="plain-field" placeholder="Full Name">
<span style="display: none;"></span>

JQuery:

function resizeInputs($text) {
    var text = $text.val().replace(/\s+/g, ' '),
        placeholder = $text.attr('placeholder'),
        span = $text.next('span');
        span.text(placeholder);
    var width = span.width();

    if(text !== '') {
        span.text(text);
    var width = span.width();
    }

    $text.css('width', width + 5);
};

Приведенная выше функция получает входное значение, обрезает лишние пробелы и устанавливает текст в интервале, чтобы получить ширину. Если текста нет, вместо этого он получает заполнитель и вводит его в диапазон. Как только он вводит текст в промежуток, он устанавливает ширину ввода. Значение + 5 по ширине объясняется тем, что без этого ввод в браузере Edge обрывается чуть-чуть.

$('.plain-field').each(function() {
    var $text = $(this);
    resizeInputs($text);
});

$('.plain-field').on('keyup blur', function() {
    var $text = $(this);
    resizeInputs($text);
});

$('.plain-field').on('blur', function() {
    var $text = $(this).val().replace(/\s+/g, ' ');
    $(this).val($text);
});

Если это можно улучшить, пожалуйста, дайте мне знать, так как это самое чистое решение, которое я мог бы придумать.

0 голосов
/ 16 мая 2018

Пуленепробиваемый, общий способ должен:

  1. Учитывать все возможные стили измеряемого input элемента
  2. Уметьприменить измерение к любому входу без изменения HTML или

Codepen demo

var getInputValueWidth = (function(){
  // https://stackoverflow.com/a/49982135/104380
  function copyNodeStyle(sourceNode, targetNode) {
    var computedStyle = window.getComputedStyle(sourceNode);
    Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
  }
  
  function createInputMeassureElm( inputelm ){
    // create a dummy input element for measurements
    var meassureElm = document.createElement('span');
    // copy the read input's styles to the dummy input
    copyNodeStyle(inputelm, meassureElm);
    
    // set hard-coded styles needed for propper meassuring 
    meassureElm.style.width = 'auto';
    meassureElm.style.position = 'absolute';
    meassureElm.style.left = '-9999px';
    meassureElm.style.top = '-9999px';
    meassureElm.style.whiteSpace = 'pre';
    
    meassureElm.textContent = inputelm.value || '';
    
    // add the meassure element to the body
    document.body.appendChild(meassureElm);
    
    return meassureElm;
  }
  
  return function(){
    return createInputMeassureElm(this).offsetWidth;
  }
})();


// delegated event binding
document.body.addEventListener('input', onInputDelegate)

function onInputDelegate(e){
  if( e.target.classList.contains('autoSize') )
    e.target.style.width = getInputValueWidth.call(e.target) + 'px';
}
input{ 
  font-size:1.3em; 
  padding:5px; 
  margin-bottom: 1em;
}

input.type2{
  font-size: 2.5em;
  letter-spacing: 4px;
  font-style: italic;
}
<input class='autoSize' value="type something">
<br>
<input class='autoSize type2' value="here too">
0 голосов
/ 11 апреля 2017

Лучше onvalue:

<input id="txt" type="text" onvalue="this.style.width = ((this.value.length + 1) * 8) + 'px';">

Также включает в себя вставку, перетаскивание и т. Д.

0 голосов
/ 21 ноября 2017

Почему бы не использовать только CSS?

<div id="wrapper">
  <input onkeyup="keyup(event)">
  <div id="ghost"></div>
</div>

function keyup(e) {
	document.getElementById('ghost').innerText = e.target.value;
}
#wrapper {
  position: relative;
  min-width: 30px;
  display: inline-block;
}

input {
  position: absolute;
  left:0;
  right:0;
  border:1px solid blue;
  width: 100%;
}

#ghost {
  color: transparent;
}
<div id="wrapper">
  <input onkeyup="keyup(event)">
  <div id="ghost"></div>
</div>
wrapper {
  position: relative;
  min-width: 30px;
  border: 1px solid red;
  display: inline-block;
}

input {
  position: absolute;
  left:0;
  right:0;
  width: 100%;
}

#ghost {
  color: transparent;
}

этот код был представлен @Iain Todd, и я подумал, что должен поделиться им

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...