最近在工作中遇到这个问题了,网上找了一些解决方案,全都试了一遍,有些没用有些有用,在此把靠谱的方法写出来。
一.div模拟textarea以实现高度自适应
CSS代码:
.test_box {
400px;
min-height: 120px;
max-height: 300px;
_height: 120px;
margin-left: auto;
margin-right: auto;
padding: 3px;
outline: 0;
border: 1px solid #a0b3d6;
font-size: 12px;
word-wrap: break-word;
overflow-x: hidden;
overflow-y: auto;
-webkit-user-modify: read-write-plaintext-only;
}
HTML代码:
<div class="test_box" contenteditable="true"><br /></div>
JS代码:
if (typeof document.webkitHidden == "undefined") { // 非chrome浏览器阻止粘贴 box.onpaste = function() { return false; } }
注意事项:
1.焦点:outline:0;
2.清除p标签的margin值:.test_box p{ margin: 0; }
3.可编辑模式的div标签与textarea一样,是支持focus, blur事件的。自然也支持focus伪类,demo页面中Firefox等现代浏览器获取焦点时的外发光就是使用的:focus。
二.用JS控制来实现:方法一
<
script
type
=
"text/javascript"
>
//基本函数*2
var addHandler = window.addEventListener?
function(elem,event,handler){elem.addEventListener(event,handler);}:
function(elem,event,handler){elem.attachEvent("on"+event,handler);};
var $ = function(id){return document.getElementById(id);}
function autoTextArea(elemid){
//新建一个textarea用户计算高度
if(!$("_textareacopy")){
var t = document.createElement("textarea");
t.id="_textareacopy";
t.style.position="absolute";
t.style.left="-9999px";
document.body.appendChild(t);
}
function change(){
$("_textareacopy").value= $(elemid).value;
$(elemid).style.height= $("_textareacopy").scrollHeight+$("_textareacopy").style.height+"px";
}
addHandler($("target"),"propertychange",change);//for IE
addHandler($("target"),"input",change);// for !IE
$(elemid).style.overflow="hidden";//一处隐藏,必须的。
$(elemid).style.resize="none";//去掉textarea能拖拽放大/缩小高度/宽度功能
}
addHandler(window,"load",function(){
autoTextArea("target");
});
</
script
>
<
textarea
id
=
"target"
rows
=
""
cols
=
""
></
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>