每按一次键,textarea 高度会自动增加,但文字内容并未增加,为何高度会变?
代码于下连结 jsbin
jsbin 于此展现
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<textarea onclick='go(this)' onkeyup='go(this)'>d545451511515151515
5151kfjjfkdkdksk</textarea>
</body>
</html>
css
textarea {
//border: 2px solid #ccc;
padding: 5px;
vertical-align: top;
// width: 95%;
height: 40px;
background-color: #FFFFCC;
width: 110px;
border: 12px solid #EBEBEB;
OVERFLOW: hidden;
}
javascript
function go(xx){
xx.style.height=xx.scrollHeight+ 'px'
//xx.style.height=xx.clientHeight+ 'px';
//alert (xx.style.height);
}
clientHeight 获取对象可视区高度包括padding,不包括滚动条,不包括边框
scrollHeight 获取的是真实内容的高度
导致这种情况的原因是 textarea 默认height设置的内容content的高度 不包括padding 所以会一直增加
加上box-sizing: border-box; 就不会出现这种情况