我正在尝试将自动增长动画效果的类添加到 textarea 元素。
演示: http://jsfiddle.net/d0kmg7d3/15/
var tx = document.getElementsByTagName('textarea');
for (var i = 0; i < tx.length; i++) {
tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
tx[i].addEventListener("input", OnInput, false);
}
function OnInput(e) {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
}
如何只在触发高度时才切换动画? 沿着这条线的东西:
this.classList.toggle("horizTranslate")
但是我如何检测高度何时发生变化?
最佳答案
也许你不需要,JS来做这个,用纯css你可以做到,唯一需要关心的是transition
和max-height
CSS 属性。
我刚刚修改了你例子中的代码,希望能帮到你。
请参阅下面的代码。
var tx = document.getElementsByTagName('textarea');
/*for (var i = 0; i < tx.length; i++) {
tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
tx[i].addEventListener("input", OnInput, false);
}*/
function OnInput(e) {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
}
textarea {
max-height: 40px;
height: 500px;
transition: max-height 0.5s;
appearance: none;
-webkit-appearance: none;
border: 1px solid rgba(0, 0, 0, 0.5);
border-radius: 3px;
padding: .5em;
font-size: 1em;
}
textarea:focus {
background: orange;
height: 200px;
max-height: 200px;
}
body {
font-family: sans-serif;
font-size: 16px;
}
<textarea class="horizTranslate" placeholder="Type, paste, cut text here..."></textarea>
关于javascript - 在特定操作上使用 javascript 运行 css 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46841277/