其实现代浏览器大多都支持文本框尺寸调节功能,绝大多数情况下却没有自动适应来得爽快,在网络上发现一方法比较简单的实现文本框高度自适应,于是封装了这个函数,准备以后应用到项目中。
源代码:
23:03文章更新:
感谢alucelx同学再次给力的帮助,大大简化了方法,更新代码为0.2版本,同时解决了兼容opera浏览器,至此全兼容ie6+与现代浏览器!
在线演示: http://demo.jb51.net/js/2011/autoarea/index.htm
autotextarea.js
测试代码:
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>文本框根据输入内容自适应高度</title>
<style type="text/css">
#textarea { font: 1.4em/1.8em arial; overflow: hidden; width: 550px; height: 6em; padding:10px; }
</style>
<script src="autotextarea.js"></script>
</head>
<body style="background:#fbfcfd url(http://goo.gl/klszx);">
<textarea id="textarea"></textarea>
<script>
var text = document.getelementbyid("textarea"),
tip = '想写点什么..';
autotextarea(text);// 调用
text.value = tip;
text.onfocus = function () {
if (text.value === tip) text.value = '';
};
text.onblur = function () {
if (text.value === '') text.value = tip;
};
</script>
</body>
</html>
发表评论