我有一个jQuery编码的textarea,每行限制字符数为11,自动调整大小取决于行。
当点击Enter添加新行时,它会增加2或3行(假设只添加1行),当用户点击“Enter”时,该数字会不断增加。
$(document).ready(function(){
var textArea = $('#foo');
//var maxRows = textArea.attr('rows');
var maxChars = textArea.attr('cols');
textArea.keypress(function(e){
var text = textArea.val();
var lines = text.split('\n');
if (e.keyCode == 13){
//return lines.length < maxRows;
}
else{ //Should check for backspace/del/etc.
var caret = textArea.get(0).selectionStart;
console.log(caret);
var line = 0;
var charCount = 0;
$.each(lines, function(i,e){
charCount += e.length;
if (caret <= charCount){
line = i;
return false;
}
//\n count for 1 char;
charCount += 1;
});
var theLine = lines[line];
return theLine.length < maxChars;
}
});
});
// Applied globally on all textareas with the "autoExpand" class
$(document)
.one('focus.autoExpand', 'textarea.autoExpand', function(){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.autoExpand', 'textarea.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0, rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 17);
this.rows = minRows + rows;
});
.ta {
background-color:#d5d5d5;
padding:10px;
}
#foo {
background: transparent url(http://s24.postimg.org/62v2ipx81/underline.png) repeat;
border:none;
display:block;
font-size:18px;
box-sizing: content-box;
height:auto;
width:300px;
overflow:hidden;
line-height:30px;
font-weight:bold;
white-space: nowrap;
color:black;
resize: none;
outline-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ta">
I like my name because:<br />
<textarea id="foo" class="autoExpand" cols="11" var rows="3" data-min-rows="3"></textarea>
<br />
</div>
代码位于JSfiddle here
答案 0 :(得分:2)
你每17分,但行高是30
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 30);
我看到 baseScrollHeight 为89,差异总是增加29
这里小提琴==&gt; http://jsfiddle.net/qx4qknfb/