今天需要一个回复评论的页面,设计师给的初始界面就是一个只有一行的框。然后当时就想这个交互该怎么实现比较好,然后想起了新浪微博的做法:点击评论,默认显示一行,当输入的文字超过一行或者输入Enter时,输入框的高度会随着改变,直到输入完毕。顿时觉得这个细节做得挺不错的,可以效仿下。下面分享2种实现textarea高度自适应的做法,一种是用div来模拟textarea来实现的,用CSS控制样式,不用JS;另一种是利用JS控制的(因为存在浏览器兼容问题,所以写起来比较麻烦);应该有jquery封装过的,回头研究下
谷歌、IE、Opera默认显示两行文本,火狐默认显示3行文本,行数超过两行是会出现滚动条,可以自己设定设定一些行数来进行强制多少行进行显示。
方法一:div模拟textarea文本域轻松实现高度自适应(缺点就是没有了placeholder提示语)
因为textarea不支持自适应高度,就是定好高度或者是行数之后,超出部分就会显示滚动条,看起来不美观。
而用DIV来模拟时,首先遇到的问题是:div怎么实现输入功能?
如一个普通的block元素上加个contenteditable="true"就实现编辑,出现光标了
contenteditable属性虽是HTML5里面的内容,但是IE似乎老早就支持此标签属性了。所以,兼容性方面还是不用太担心的。
<style type="text/css"> #textarea { width: 400px; min-height: 20px; max-height: 300px; _height: 120px; margin-left: auto; margin-right: auto; padding: 3px; outline: 0; border: 1px solid #a0b3d6; font-size: 12px; line-height: 24px; padding: 2px; word-wrap: break-word; overflow-x: hidden; overflow-y: auto; border-color: rgba(82, 168, 236, 0.8); box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6); } </style> <div class="textarea" contenteditable="true"><br /></div>
CSS代码中,因为IE6不支持min/max,所以做了hack
方法二:文本框textarea根据输入内容自适应高度
这个写法是用原生JS写的,考虑了很多兼容性问题,完全和新浪微博的回复效果一样的功能
<!DOCTYPE html>
<html> <head> <title>autoresizing textarea</title> <style type="text/css"> textarea { border: 0 none white; overflow: hidden; padding: 0; outline: none; background-color: #D0D0D0; resize: none; } </style> <script type="text/javascript"> var observe; if (window.attachEvent) { observe = function (element, event, handler) { element.attachEvent('on'+event, handler); }; } else { observe = function (element, event, handler) { element.addEventListener(event, handler, false); }; } function init () { var text = document.getElementById('text'); function resize () { text.style.height = 'auto'; text.style.height = text.scrollHeight+'px'; } /* 0-timeout to get the already changed text */ function delayedResize () { window.setTimeout(resize, 0); } observe(text, 'change', resize); observe(text, 'cut', delayedResize); observe(text, 'paste', delayedResize); observe(text, 'drop', delayedResize); observe(text, 'keydown', delayedResize); text.focus(); text.select(); resize(); } </script> </head> <body onload="init();"> <textarea cols="40" rows="1" style="height:25px;" id="text"></textarea> </body> </html>
利用上面的代码就可以实现初始化的时候textarea的高度自适应并且textarea在修改的时候也可以实现其高度自适应。
今天找了一个Jquery控制高度的方法,记录一下
<script type="text/javascript">
jQuery.fn.extend({
autoHeight: function(){
return this.each(function(){
var $this = jQuery(this);
if( !$this.attr('_initAdjustHeight') ){
$this.attr('_initAdjustHeight', $this.outerHeight());
}
_adjustH(this).on('input', function(){
_adjustH(this);
});
});
/**
* 重置高度
* @param {Object} elem
*/
function _adjustH(elem){
var $obj = jQuery(elem);
return $obj.css({height: $obj.attr('_initAdjustHeight'), 'overflow-y': 'hidden'})
.height( elem.scrollHeight );
}
}
});
// 使用
$(function(){
$('textarea').autoHeight();
});
</script>
.