Как сделать так, чтобы текстовое поле автоматически изменяло размер по горизонтали, чтобы соответствовать введенному тексту?
У меня есть два div рядом, оба с textareas. Я хочу, чтобы их содержание выстраивалось точно, строка за строкой. Поэтому вместо переноса текста, если строка становится длинной, я бы предпочел, чтобы текстовая область стала шире.
Я не уверен, что рассчитать, чтобы увидеть, стала ли линия слишком большой.
4 ответа
Решение
Учитывая этот HTML:
<textarea id="theID" rows=5 cols=15></textarea>
Вы можете попробовать следующее JS + jQuery:
var minCol = $('#theID').attr('cols');;
$('#theID').keyup(updateCols);
function updateCols() {
var lines = $('#theID').val().split(/\n/);
var lineMaxLenght = getLineMaxLenght(lines);
if (lineMaxLenght >= minCol) {
$('#theID').attr('cols', lineMaxLenght);
}
}
function getLineMaxLenght(lines) {
var max = -1;
for (var i = 0; i < lines.length; i++) {
if (lines[i].length > max) {
max = lines[i].length;
}
}
return max;
}
Вы можете улучшить getLineMaxLenght, используя другую библиотеку
FIDDLE
Демо из впечатляющих сетей
HTML
<p>Code explanation: <a href="http://www.impressivewebs.com/textarea-auto-resize/">Textarea Auto Resize</a></p>
<textarea id="comments" placeholder="Type many lines of texts in here and you will see magic stuff" class="common"></textarea>
JS
/*global document:false, $:false */
var txt = $('#comments'),
hiddenDiv = $(document.createElement('div')),
content = null;
txt.addClass('txtstuff');
hiddenDiv.addClass('hiddendiv common');
$('body').append(hiddenDiv);
txt.on('keyup', function () {
content = $(this).val();
content = content.replace(/\n/g, '<br>');
hiddenDiv.html(content + '<br class="lbr">');
$(this).css('height', hiddenDiv.height());
});
CSS
body {
margin: 20px;
}
p {
margin-bottom: 14px;
}
textarea {
color: #444;
padding: 5px;
}
.txtstuff {
resize: none; /* remove this if you want the user to be able to resize it in modern browsers */
overflow: hidden;
}
.hiddendiv {
display: none;
white-space: pre-wrap;
word-wrap: break-word;
overflow-wrap: break-word; /* future version of deprecated 'word-wrap' */
}
/* the styles for 'commmon' are applied to both the textarea and the hidden clone */
/* these must be the same for both */
.common {
width: 500px;
min-height: 50px;
font-family: Arial, sans-serif;
font-size: 13px;
overflow: hidden;
}
.lbr {
line-height: 3px;
}
Если вы хотите изменить ширину текстовой области, вам нужно изменить атрибут "cols".
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#txtarea").keyup(function(){
if($("#txtarea").val().length > 20){
$("#txtarea")[0].cols = $("#txtarea").val().length;
}
});
});
</script>
</head>
<body>
<textarea id="txtarea"></textarea>
</body>
</html>
Попробуй это. Также я опубликовал этот jsFiddle ( http://jsfiddle.net/xPCB4/), чтобы вы могли увидеть его в действии. Я надеюсь, что это то, что вам нужно.