我是html,css和js的新手,正在从事一些婴儿项目以获取更多经验。这次我正在学习如何在我的网站上使用javascript,但是我遇到了问题。我有一个error-msg块,我想通过转换来更改其高度。同样在js中,我添加了提供其属性的类,并在3s之后将其删除。当我添加班级时,过渡有效,但是当班级被移除时,过渡就停止工作。
.transition-msg {
max-height: 0;
overflow: hidden;
-webkit-transition: max-height 0.5s ease-in-out;
-moz-transition: max-height 0.5s ease-in-out;
-o-transition: max-height 0.5s ease-in-out;
transition: max-height 0.5s ease-in-out;
}
.error-window {
max-height: 200px;
background-color: rgb(241, 128, 128);
border: #888 solid 0.04rem;
border-radius: 0.2rem;
}
<input type="submit" name="submit" value="Sign In" class="btn">
<div id="form-msg" class="transition-msg"></div>
function onSubmit(e) {
e.preventDefault();
if(firstnameInput.value === '' || lastnameInput.value === '' || passwordInput.value === '' || emailInput.value === '' || !termsBox.checked) {
//alert('Please enter all fields');
msg.classList.add('error-window');
msg.innerHTML = '<p>Please enter all fields</p>';
// Remove error after 3 seconds
setTimeout(() => {msg.innerHTML = ''; msg.classList.remove('error-window')}, 3000);
答案 0 :(得分:1)
您的代码有两个问题。
第一个是,在CSS中,您将AAAA
属性放在了修饰符类(您的background-color
)上,并且删除了该类后,背景立即就消失了,因为过渡是仅为.error-window
设置。要解决此问题,只需将max-height
移至父类background-color
类。
动画.transition-msg
的第二个问题是,在JS代码中,您要在过渡完成之前删除HTML,因此max-height
的高度立即变为零(如果没有内容,没有高度)。
解决方案是等待div
属性的转换完成,然后删除HTML。
正在工作DEMO
基本上,这表明您可以在当前方法中使用另一种max-height
方法,但要延迟500毫秒来匹配CSS过渡,然后删除HTML。
setTimeout()
答案 1 :(得分:-1)
请使用到主类的过渡 在这里:
.transition-msg {
max-height: 0;
overflow: hidden;
}
.error-window {
max-height: 200px;
background-color: rgb(241, 128, 128);
border: #888 solid 0.04rem;
border-radius: 0.2rem;
-webkit-transition: max-height 0.5s ease-in-out;
-moz-transition: max-height 0.5s ease-in-out;
-o-transition: max-height 0.5s ease-in-out;
transition: max-height 0.5s ease-in-out;
}