次のように、cssで初期テキスト入力サイズを設定できます。
width: 50px;
しかし、たとえば200pxに達するまで、入力すると大きくなります。これはストレートcss、htmlで、できればjavascriptなしで実行できますか?
もちろん、js / jqueryソリューションも投稿してください。ただし、これがなくても実行できる場合は、それはすばらしいことです。
ここで私の試み:
次のように、cssで初期テキスト入力サイズを設定できます。
width: 50px;
しかし、たとえば200pxに達するまで、入力すると大きくなります。これはストレートcss、htmlで、できればjavascriptなしで実行できますか?
もちろん、js / jqueryソリューションも投稿してください。ただし、これがなくても実行できる場合は、それはすばらしいことです。
ここで私の試み:
回答:
これはCSSとコンテンツ編集可能のみの例です:
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
はより簡単で信頼性が高いと思います。
From:テキストフィールド用の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);
ここでは、このようなことを試すことができます
編集:改訂された例(1つの新しいソリューションを追加) 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に設定するだけです。