2017-10-20 44 views
1

我试图为autogrow动画效果添加一个类到textarea元素。在特定动作上用javascript运行css动画

演示: 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") 

,但我怎样检测时,高度改变?

+0

你是什么高度意味着被触发?你的意思是当文本区域的文本超过了框的高度? – Vincent1989

+0

所以在该演示中,当添加新文本时,textarea会增加。我试图添加一个动画/类到那一刻,所以文本框不跳,但它顺利改变高度。那有意义吗?。 – user2513846

回答

-1

也许你不需要,JS做到这一点,用纯CSS你可以做到这一点,唯一与你需要关心transitionmax-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>

+0

嗨,是的,我知道如何添加这样的转换。问题是,在添加更多字符的时候,实际高度被调整大小时,我无法添加相同的动画。你懂我的意思吗?这就是为什么我在考虑使用JS切换功能。 – user2513846