最近项目遇到一个说小不小说大不大的问题,输入框要自动换行,并且高度还得自适应,我试了几种方式,
1.input 输入,input不能换行,上网查询了说将css设为word-break: break-all; word-wrap:break-word;也是无效的。
2.div 设置contenteditable=”true”属性,这种方法可以实现输入内容自动换行,并且自适应高度,但是项目需要光标从边输入,我试过text-align:right是无效的。所以这种方式也不行。
3.textarea,文本输入框,想想这个应该可以了吧,文本输入框是可以内容自动换行,可是高度怎么都是固定的啊。我还是没解决。百度吧,终于找到解决办法啦。
最后遇到一个光标在placeholder提示文字上面,解决办法:#
textarea::-webkit-input-placeholder{ padding-right: 4px;}
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title></title>
<style>
#textarea {
display: block;
margin:0 auto;
overflow: hidden;
width: 550px;
font-size: 14px;
height: 18px;
line-height: 24px;
padding:2px;
text-align: right;
}
textarea {
outline: 0 none;
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>
</head>
<body>
<textarea id=”textarea” placeholder=”回复内容”></textarea>
<script>
var autoTextarea = function (elem, extra, maxHeight) {
extra = extra || 0;
var isFirefox = !!document.getBoxObjectFor || ‘mozInnerScreenX’ in window,
isOpera = !!window.opera && !!window.opera.toString().indexOf(‘Opera’),
addEvent = function (type, callback) {
elem.addEventListener #
elem.addEventListener(type, callback, false) :
elem.attachEvent(‘on’ + type, callback);
},
getStyle = elem.currentStyle # function (name) {
var val = elem.currentStyle[name];
if (name === ‘height’ && val.search(/px/i) !== 1) {
var rect = elem.getBoundingClientRect();
return rect.bottom – rect.top –
parseFloat(getStyle(‘paddingTop’)) –
parseFloat(getStyle(‘paddingBottom’)) + ‘px’;
};
return val;
} : function (name) {
return getComputedStyle(elem, null)[name];
},
minHeight = parseFloat(getStyle(‘height’));
elem.style.resize = ‘none’;
var change = function () {
var scrollTop, height,
padding = 0,
style = elem.style;
if (elem._length === elem.value.length) return;
elem._length = elem.value.length;
if (!isFirefox && !isOpera) {
padding = parseInt(getStyle(‘paddingTop’)) + parseInt(getStyle(‘paddingBottom’));
};
scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
elem.style.height = minHeight + ‘px’;
if (elem.scrollHeight > minHeight) {
if (maxHeight && elem.scrollHeight > maxHeight) {
height = maxHeight – padding;
style.overflowY = ‘auto’;
} else {
height = elem.scrollHeight – padding;
style.overflowY = ‘hidden’;
};
style.height = height + extra + ‘px’;
scrollTop += parseInt(style.height) – elem.currHeight;
document.body.scrollTop = scrollTop;
document.documentElement.scrollTop = scrollTop;
elem.currHeight = parseInt(style.height);
};
};
addEvent(‘propertychange’, change);
addEvent(‘input’, change);
addEvent(‘focus’, change);
change();
};
</script>
<script>
var text = document.getElementById(“textarea”);
autoTextarea(text);// 调用
</script>
</body>
</html>