div模拟textarea文本域实现高度自适应
一个普通的block元素上加个contenteditable="true",contenteditable
属性规定元素内容是否可编辑。
HTML
<div class="textarea" contenteditable="true"></div>
CSS
.textarea{
width: 400px;
min-height: 120px; /*最小高度*/
max-height: 300px; /*最大高度,超出滚动条*/
margin: 0 auto;
outline: 0; /*去除获焦时的虚框*/
border: 1px solid #a0b3d6;
font-size: 12px;
word-wrap: break-word;
overflow-x: hidden;
overflow-y: auto;
}
.box p{
margin: 0; /*清除ie6-8下自动生成的<p>标签的默认margin*/
}
HTML字符过滤(JS)
$('[contenteditable]').each(function() {
// 干掉IE http之类地址自动加链接
try {
document.execCommand("AutoUrlDetect", false, false);
} catch (e) {}
$(this).on('paste', function(e) {
e.preventDefault();
var text = null;
if(window.clipboardData && clipboardData.setData) { //剪切板
// IE
text = window.clipboardData.getData('text');
} else {
//chrome、firefox
text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('在这里输入文本');
}
if (document.body.createTextRange) {
if (document.selection) {
textRange = document.selection.createRange();
} else if (window.getSelection) {
sel = window.getSelection();
var range = sel.getRangeAt(0);
// 创建临时元素,使得TextRange可以移动到正确的位置
var tempEl = document.createElement("span");
tempEl.innerHTML = "&#FEFF;";
range.deleteContents();
range.insertNode(tempEl);
textRange = document.body.createTextRange();
textRange.moveToElementText(tempEl);
tempEl.parentNode.removeChild(tempEl);
}
textRange.text = text;
textRange.collapse(false);
textRange.select();
} else {
// Chrome之类浏览器
document.execCommand("insertText", false, text);
}
});
// 去除Crtl+b/Ctrl+i/Ctrl+u等快捷键
$(this).on('keydown', function(e) {
// e.metaKey for mac
if (e.ctrlKey || e.metaKey) {
switch(e.keyCode){
case 66: //ctrl+B or ctrl+b
case 98:
case 73: //ctrl+I or ctrl+i
case 105:
case 85: //ctrl+U or ctrl+u
case 117: {
e.preventDefault();
break;
}
}
}
});
});
转载至https://www.zhangxinxu.com/wordpress/2010/12/div-textarea-height-auto/