Jquery插件----TextArea高度自适应

textArea的高度自适应本来应该很简单的,只需要用js监听它的输入然后修改其高度即可,甚至对于ie只要用css(overflow:visible;)控制就可以了。但是同样会有兼容性问题,用一个jQuery插件来实现。代码如下:

$.fn.extend({

textareaAutoHeight: function (options) {

this._options = {

minHeight: 0,

maxHeight: 1000

}

this.init = function () {

for (var p in options) {

this._options[p] = options[p];

}

if (this._options.minHeight == 0) {

this._options.minHeight=parseFloat($(this).height());

}

for (var p in this._options) {

if ($(this).attr(p) == null) {

$(this).attr(p, this._options[p]);

}

}

$(this).keyup(this.resetHeight).change(this.resetHeight)

.focus(this.resetHeight);

}

this.resetHeight = function () {

var _minHeight = parseFloat($(this).attr("minHeight"));

var _maxHeight = parseFloat($(this).attr("maxHeight"));

if (!$.browser.msie) {

$(this).height(0);

}

var h = parseFloat(this.scrollHeight);

h = h < _minHeight ? _minHeight :

h > _maxHeight ? _maxHeight : h;

$(this).height(h).scrollTop(h);

if (h >= _maxHeight) {

$(this).css("overflow-y", "scroll");

}

else {

$(this).css("overflow-y", "hidden");

}

}

this.init();

}

});

需要引用jQuery文件,使用方法很简单,比如:

<textarea id="textarea1"></textarea>

<textarea id="textarea2"></textarea>

<textarea id="textarea3"></textarea>

<script>

//最小高度和最大高度默认

$("#textarea1").textareaAutoHeight();

//最大高度为100px

$("#textarea2").textareaAutoHeight({ maxHeight:100 });

//最小高度为50px,最大高度为200px

$("#textarea3").textareaAutoHeight({ minHeight:50, maxHeight:200 });

</script>

这里有个特别奇怪的现象,就是在非ie下如果不先将textarea的高度改为0,获取到的scrollHeight就是不正常

更多技术文章

posted @ 2015-03-11 15:29  梨花寨  阅读(666)  评论(0编辑  收藏  举报