我有可设置的div,溢出设置为隐藏,我希望div在用户输入时展开(如果需要)。每次高度变化时,我都使用jquery来改变div的类。 我似乎无法开始工作,它会让班级变得更好但没有任何反应
HTML:
<div class="contanier">
<div class="1" id="msgWriteArea" contenteditable="true"></div>
</div>
CSS:
#msgWriteArea{
outline: 0;
border: none;
resize: none;
width: 100%;
height:20px;
line-height:20px;
font-size:18px;
border:solid 1px #000;
background:#FFF;
}
.contanier .1{
height:20px;
overflow:hidden;
}
.contanier .2{
height:40px;
overflow:hidden;
}
.contanier .3{
height:60px;
overflow:hidden;
}
.contanier .4{
height:80px;
overflow:hidden;
}
.contanier .5{
height:80px;
overflow-y:scroll;
}
使用Javascript:
var chatBoxSize = {
oldHeight : 0,
scrollHeight : 0,
lastClass : 1,
maxClass : 5
};
function updateChatSize() {
var id = '#msgWriteArea';
var element = document.querySelector(id);
if((element.offsetHeight < element.scrollHeight) || (element.offsetWidth < element.scrollWidth)){
if(chatBoxSize.lastClass == null){
//add size 1
console.log('ADD SIZE 1');
$(id).addClass('1');
chatBoxSize.lastClass = '1';
} else if(chatBoxSize.oldHeight != $(id)[0].scrollHeight){
//get the correct size to add
if(parseInt(current) >= parseInt(chatBoxSize.maxClass)){
var current = chatBoxSize.maxClass,
last = parseInt(chatBoxSize.maxClass) - 1;
chatBoxSize.lastClass = current;
console.log('IS AT MAX SIZE');
} else if(chatBoxSize.scrollHeight < $(id)[0].scrollHeight){
var current = parseInt(chatBoxSize.lastClass) + 1,
last = parseInt(chatBoxSize.lastClass);
chatBoxSize.lastClass = current;
} else if(chatBoxSize.scrollHeight > $(id)[0].scrollHeight) {
var current = parseInt(chatBoxSize.lastClass) - 1,
last = parseInt(chatBoxSize.lastClass);
chatBoxSize.lastClass = current;
} else {
//console.log('No Change in height');
}
if(last != undefined){
console.log('Add', current, 'Remove', last);
$('#msgWriteArea').addClass(current + "");
$('#msgWriteArea').removeClass(last + "");
$('#display').val('Add ' + current + ' Remove' + last);
}
}
chatBoxSize.oldHeight = element.offsetHeight;
chatBoxSize.scrollHeight = $(id)[0].scrollHeight;
chatBoxSize.oldHeight = element.offsetHeight;
}
};
$(function (){
$('#msgWriteArea').bind('change keydown input', function () {
if(event.type == 'keydown'){
updateChatSize();
}
});
});
这是较大页面的一部分。因此,需要让班级改变其他元素,但现在只需要一个就可以了解其工作原理