입력 할 때 html 텍스트 입력 필드가 커지나요?
다음과 같이 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>
나는 당신을 위해 이것을 썼습니다, 나는 당신이 그것을 좋아하기를 바랍니다 :) 그것이 크로스 브라우저라는 보장은 없지만 나는 그것이 있다고 생각합니다 :)
(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);
}
})();
입력의 크기 속성을 프로그래밍 방식으로 수정하는 것은 어떻습니까?
의미 론적으로 (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);
}
});
몇 가지가 떠 오릅니다.
onkeydown
텍스트 필드에서 핸들러를 사용 하고 텍스트 *를 측정 한 다음 그에 따라 텍스트 상자 크기를 늘립니다.
:focus
너비가 더 큰 텍스트 상자에 CSS 클래스를 첨부 하십시오. 그러면 초점을 맞출 때 상자가 더 커집니다. 그것은 정확히 당신이 요구하는 것은 아니지만 유사합니다.
* 자바 스크립트에서 텍스트를 측정하는 것은 간단하지 않습니다. 이 질문 에서 몇 가지 아이디어를 확인하십시오 .
보낸 사람 : 텍스트 필드 용 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);
표시 할 범위를 설정하면 : 인라인 블록, 자동 가로 및 세로 크기 조정이 매우 잘 작동합니다.
<span contenteditable="true"
style="display: inline-block;
border: solid 1px black;
min-width: 50px;
max-width: 200px">
</span>
여기에서 이와 같은 것을 시도 할 수 있습니다.
편집 : 수정 된 예제 (하나의 새로운 솔루션 추가) 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의 너비를 계산 한 다음 멋진 애니메이션을 사용하는 것입니다. 여유 효과는 입력 필드 너비를 업데이트합니다. 유일한 단점은 사용자가 입력하는 동안 입력 필드가 "작게"유지된다는 것입니다. 또는 시간 제한을 추가 할 수 있습니다. :) 위의 바이올린에서도 이러한 종류의 솔루션을 확인할 수 있습니다!
나는 이것이 심각하게 오래된 게시물이라는 것을 알고 있지만 어쨌든 내 대답은 다른 사람들에게 유용 할 수 있으므로 여기에 있습니다. contenteditable div에 대한 내 CSS 스타일 정의가 높이 200 대신 200의 최소 높이를 가지면 div가 자동으로 확장된다는 것을 발견했습니다.
물론 사용하는 접근 방식은 최종 목표가 무엇인지에 따라 다릅니다. 양식과 함께 결과를 제출하려는 경우 기본 양식 요소를 사용하면 제출을 위해 스크립팅을 사용할 필요가 없습니다. 또한 스크립팅이 꺼져 있으면 멋진 성장 축소 효과없이 폴 백이 계속 작동합니다. contenteditable 요소 에서 일반 텍스트를 얻으려면 항상 node.textContent 와 같은 스크립팅을 사용 하여 브라우저가 사용자 입력에 삽입하는 html을 제거 할 수 있습니다 .
This version uses native form elements with slight refinements on some of the previous posts.
It allows the content to shrink as well.
Use this in combination with CSS for better control.
<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';
};
});
You can use something similar with <textarea> elements
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';
};
});
This doesn't flicker on Chrome, results may vary on other browsers, so test.
If you are just interested in growing, you can update the width
to scrollWidth
, whenever the content of the input
element changes.
document.querySelectorAll('input[type="text"]').forEach(function(node) {
node.onchange = node.oninput = function() {
node.style.width = node.scrollWidth+'px';
};
});
But this will not shrink the element.
Here's a method that worked for me. When you type into the field, it puts that text into the hidden span, then gets its new width and applies it to the input field. It grows and shrinks with your input, with a safeguard against the input virtually disappearing when you erase all input. Tested in Chrome. (EDIT: works in Safari, Firefox and Edge at the time of this edit)
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>
참고URL : https://stackoverflow.com/questions/7168727/make-html-text-input-field-grow-as-i-type
'Development Tip' 카테고리의 다른 글
Ruby 기호와 동등한 Python이 있습니까? (0) | 2020.11.11 |
---|---|
파일에서 이미지를 연 다음 잠금을 해제 하시겠습니까? (0) | 2020.11.10 |
C에서 char 배열을 복사하는 방법은 무엇입니까? (0) | 2020.11.10 |
Lambda : 로컬 변수에는 최종, 인스턴스 변수는 필요하지 않습니다. (0) | 2020.11.10 |
약속-약속을 강제로 취소 할 수 있습니까? (0) | 2020.11.10 |