嗨,我有这个自动扩展textarea
jquery代码,目前,除了谷歌Chrome之外,它在某种程度上工作.
问题是当我将样式填充:3px添加到textarea时,每当我在框中键入内容时,它将扩展高度.如果我删除样式填充,它将很好地工作.
测试在这里:(使用谷歌浏览器进行测试)
(function($) {
// jQuery plugin definition
$.fn.TextAreaExpander = function(minHeight, maxHeight) {
var hCheck = !($.browser.msie || $.browser.opera);
// resize a textarea
function ResizeTextarea(e) {
// event or initialize element?
e = e.target || e;
// find content length and box width
var vlen = e.value.length, ewidth = e.offsetWidth;
if( vlen != e.valLength || ewidth != e.boxWidth ) {
$("#msg").html(e.boxWidth);
if( hCheck && (vlen < e.valLength || ewidth != e.boxWidth) ) e.style.height = "0px";
var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));
e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
e.style.height = h + "px";
e.valLength = vlen;
e.boxWidth = ewidth;
}
return true;
}
// initialize
this.each(function( ) {
// is a textarea?
if (this.nodeName.toLowerCase( ) != "textarea") return;
// set height restrictions
var p = this.className.match(/expand(\d+)\-*(\d+)*/i);
this.expandMin = minHeight || (p ? parseInt('0'+p[1], 10) : 0);
this.expandMax = maxHeight || (p ? parseInt('0'+p[2], 10) : 99999);
// initial resize
ResizeTextarea(this);
// zero vertical padding and add events
if (!this.Initialized) {
this.Initialized = true;
//$(this).css("padding-top", 0).css("padding-bottom", 0);
$(this).bind("keyup", ResizeTextarea)
.bind("focus", ResizeTextarea)
.bind("input", ResizeTextarea);
}
});
return this;
};
})(jQuery);
$(document).ready( function( ) {
$("#message").TextAreaExpander(40);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<style>
.textfield {
padding:3px 3px;
width:98%;
}
</style>
<textarea id="message" class="expand textfield"></textarea>
<div id="msg"></div>
我一直试图找出原因,如果有人能在这里说清楚,我会很感激.
最佳答案 我建议您使用此插件:
http://plugins.jquery.com/project/TextAreaResizer
StackOverflow将此插件用于其textareas!我还需要说更多吗?
希望这可以帮助.干杯
PS:或者,你可以使用autogrow plugin