다음과 같이 CSS로 초기 텍스트 입력 크기를 설정할 수 있습니다.
width: 50px;
그러나 예를 들어 200px에 도달 할 때까지 입력하면 성장하고 싶습니다. 이것은 가급적 javascript없이 직접 CSS, html로 수행 할 수 있습니까?
물론 js / jquery 솔루션도 게시하십시오. 그러나 이것이 없이도 가능하다면 훌륭합니다.
내 시도 :
다음과 같이 CSS로 초기 텍스트 입력 크기를 설정할 수 있습니다.
width: 50px;
그러나 예를 들어 200px에 도달 할 때까지 입력하면 성장하고 싶습니다. 이것은 가급적 javascript없이 직접 CSS, html로 수행 할 수 있습니까?
물론 js / jquery 솔루션도 게시하십시오. 그러나 이것이 없이도 가능하다면 훌륭합니다.
내 시도 :
답변:
다음은 CSS 및 Content Editable 만있는 예입니다 .
CSS
span
{
border: solid 1px black;
}
div
{
max-width: 200px;
}
HTML
<div>
<span contenteditable="true">sdfsd</span>
</div>
span에 의해 div. word-wrap: break-word필요하거나 더 긴 단어 max-width가 div 상자를 넘칠 것임을 유의하십시오 . jsfiddle.net/YZPmC/157
나는 당신을 위해 이것을 썼습니다, 나는 당신이 그것을 좋아하기를 바랍니다 :) 그것이 크로스 브라우저라는 보장은 없지만 나는 그것이 있다고 생각합니다 :)
(function(){
var min = 100, max = 300, pad_right = 5, input = document.getElementById('adjinput');
input.style.width = min+'px';
input.onkeypress = input.onkeydown = input.onkeyup = function(){
var input = this;
setTimeout(function(){
var tmp = document.createElement('div');
tmp.style.padding = '0';
if(getComputedStyle)
tmp.style.cssText = getComputedStyle(input, null).cssText;
if(input.currentStyle)
tmp.style.cssText = input.currentStyle.cssText;
tmp.style.width = '';
tmp.style.position = 'absolute';
tmp.innerHTML = input.value.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/ /g, ' ');
input.parentNode.appendChild(tmp);
var width = tmp.clientWidth+pad_right+1;
tmp.parentNode.removeChild(tmp);
if(min <= width && width <= max)
input.style.width = width+'px';
}, 1);
}
})();
id='adjinput'
입력의 크기 속성을 프로그래밍 방식으로 수정하는 것은 어떻습니까?
의미 론적으로 (imo),이 솔루션은 사용자 입력을 위해 입력 필드를 사용하지만 약간의 jQuery를 도입하기 때문에 허용 된 솔루션보다 낫습니다. Soundcloud는 태그 지정을 위해 이와 유사한 작업을 수행합니다.
<input size="1" />
$('input').on('keydown', function(evt) {
var $this = $(this),
size = parseInt($this.attr('size'), 10),
isValidKey = (evt.which >= 65 && evt.which <= 90) || // a-zA-Z
(evt.which >= 48 && evt.which <= 57) || // 0-9
evt.which === 32;
if ( evt.which === 8 && size > 0 ) {
// backspace
$this.attr('size', size - 1);
} else if ( isValidKey ) {
// all other keystrokes
$this.attr('size', size + 1);
}
});
value.length이 더 쉽고 신뢰할 수 있다고 생각합니다 .
보낸 사람 : 텍스트 필드 용 jQuery 자동 증가 플러그인이 있습니까?
여기에서 데모보기 : http://jsbin.com/ahaxe
플러그인 :
(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, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
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);
여기에서 이와 같은 것을 시도 할 수 있습니다.
편집 : 수정 된 예제 (하나의 새로운 솔루션 추가) http://jsfiddle.net/jszjz/10/
코드 설명
var jqThis = $('#adjinput'), //object of the input field in jQuery
fontSize = parseInt( jqThis.css('font-size') ) / 2, //its font-size
//its min Width (the box won't become smaller than this
minWidth= parseInt( jqThis.css('min-width') ),
//its maxWidth (the box won't become bigger than this)
maxWidth= parseInt( jqThis.css('max-width') );
jqThis.bind('keydown', function(e){ //on key down
var newVal = (this.value.length * fontSize); //compute the new width
if( newVal > minWidth && newVal <= maxWidth ) //check to see if it is within Min and Max
this.style.width = newVal + 'px'; //update the value.
});
CSS도 꽤 간단합니다.
#adjinput{
max-width:200px !important;
width:40px;
min-width:40px;
font-size:11px;
}
편집 : 또 다른 해결책은 사용자가 원하는 것을 입력하고 흐림 (초점)하고 문자열을 (동일한 글꼴 크기로) div에 배치하고 div의 너비를 계산 한 다음 멋진 애니메이션을 사용하는 것입니다. 여유 효과는 입력 필드 너비를 업데이트합니다. 유일한 단점은 사용자가 입력하는 동안 입력 필드가 "작게"유지된다는 것입니다. 또는 시간 제한을 추가 할 수 있습니다. :) 위의 바이올린에서도 이러한 종류의 솔루션을 확인할 수 있습니다!
font-size완벽한 솔루션이 아닙니다. 나쁘지 않고 확실히 투표 할 가치가 없지만 문자를 i여러 번 입력 하면 크기가 매우 왜곡 된 결과를 볼 수 있습니다. 이에 대한 수정 사항은 내 대답을 참조하십시오.
물론 사용하는 접근 방식은 최종 목표가 무엇인지에 따라 다릅니다. 양식과 함께 결과를 제출하려는 경우 기본 양식 요소를 사용하면 제출을 위해 스크립팅을 사용할 필요가 없습니다. 또한 스크립팅이 꺼져 있으면 멋진 성장 축소 효과없이 폴 백이 여전히 작동합니다. contenteditable 요소 에서 일반 텍스트를 얻으려면 항상 node.textContent 와 같은 스크립팅을 사용 하여 브라우저가 사용자 입력에 삽입하는 html을 제거 할 수 있습니다 .
이 버전은 이전 게시물 중 일부를 약간 개선 한 기본 양식 요소를 사용합니다.
콘텐츠도 축소 할 수 있습니다.
더 나은 제어를 위해 CSS와 함께 사용하십시오.
<html>
<textarea></textarea>
<br>
<input type="text">
<style>
textarea {
width: 300px;
min-height: 100px;
}
input {
min-width: 300px;
}
<script>
document.querySelectorAll('input[type="text"]').forEach(function(node) {
var minWidth = parseInt(getComputedStyle(node).minWidth) || node.clientWidth;
node.style.overflowX = 'auto'; // 'hidden'
node.onchange = node.oninput = function() {
node.style.width = minWidth + 'px';
node.style.width = node.scrollWidth + 'px';
};
});
<textarea> 요소와 비슷한 것을 사용할 수 있습니다.
document.querySelectorAll('textarea').forEach(function(node) {
var minHeight = parseInt(getComputedStyle(node).minHeight) || node.clientHeight;
node.style.overflowY = 'auto'; // 'hidden'
node.onchange = node.oninput = function() {
node.style.height = minHeight + 'px';
node.style.height = node.scrollHeight + 'px';
};
});
Chrome에서는 깜박이지 않으며 다른 브라우저에서는 결과가 다를 수 있으므로 테스트하세요.
나를 위해 일한 방법이 있습니다. 필드에 입력하면 해당 텍스트를 숨겨진 범위에 넣은 다음 새 너비를 가져와 입력 필드에 적용합니다. 모든 입력을 지울 때 입력이 사실상 사라지는 것을 방지하기 위해 입력에 따라 확장 및 축소됩니다. Chrome에서 테스트되었습니다. (편집 :이 편집 당시 Safari, Firefox 및 Edge에서 작동합니다)
function travel_keyup(e)
{
if (e.target.value.length == 0) return;
var oSpan=document.querySelector('#menu-enter-travel span');
oSpan.textContent=e.target.value;
match_span(e.target, oSpan);
}
function travel_keydown(e)
{
if (e.key.length == 1)
{
if (e.target.maxLength == e.target.value.length) return;
var oSpan=document.querySelector('#menu-enter-travel span');
oSpan.textContent=e.target.value + '' + e.key;
match_span(e.target, oSpan);
}
}
function match_span(oInput, oSpan)
{
oInput.style.width=oSpan.getBoundingClientRect().width + 'px';
}
window.addEventListener('load', function()
{
var oInput=document.querySelector('#menu-enter-travel input');
oInput.addEventListener('keyup', travel_keyup);
oInput.addEventListener('keydown', travel_keydown);
match_span(oInput, document.querySelector('#menu-enter-travel span'));
});
#menu-enter-travel input
{
width: 8px;
}
#menu-enter-travel span
{
visibility: hidden;
position: absolute;
top: 0px;
left: 0px;
}
<div id="menu-enter-travel">
<input type="text" pattern="^[0-9]{1,4}$" maxlength="4">KM
<span>9</span>
</div>
여러분이해야 할 일은 입력 할 때 확장하려는 입력 필드의 요소를 가져오고 CSS에서 입력 너비를 자동으로 설정하고 최소 너비를 50px로 설정하는 것입니다.