[英]Can't trigger transition by toggling classes with jQuery
I want to make a simple transition but struggle doing it with jQuery. 我想进行一个简单的过渡,但是很难用jQuery做到这一点。 I create the element that is to be transformed in JS in an eventListener like so:
我像这样在eventListener中创建要在JS中转换的元素:
const searchHint = `
<h3 id="search_hint" class="invizible">
Enter a search term to continue!
</h3>
`
$('#search_label').append(searchHint)
$('#search_hint').removeClass('invizible').addClass('make_vizible')
In my stylesheet I've got those styles for the classes 'invizible' and 'make_vizible': 在我的样式表中,我为“ invizible”和“ make_vizible”类提供了这些样式:
#search_hint.invizible {
color: white;
transition: color 1s ease;
}
#search_hint.make_vizible {
color: #404040;
}
As I understand, this should result in the search hint element slowly fading in. I create it with the invizible class, where a transition attribute is present and also a start value for the attribute to be transformed. 据我了解,这将导致搜索提示元素逐渐淡入。我使用不可见的类创建它,其中存在过渡属性,并且还包含要转换的属性的起始值。 Then I switch the classes, to a class with a different color value.
然后,我将类切换到具有不同颜色值的类。
What happens, is that the element is just displayed, not animated. 发生的是该元素只是显示而不是动画。
Any ideas? 有任何想法吗?
There are two issues: 有两个问题:
The transition
property is set in invizible
class. transition
属性在invizible
类中设置。 So once you remove it, that property is not applicable. 因此,一旦删除它,该属性将不适用。 To resolve this, associate the
transition
to the element id. 要解决此问题,请将
transition
与元素ID相关联。
The removeClass
and addClass
are probably getting applied to the same frame that appends #search_hint
while rendering. removeClass
和addClass
可能会应用于渲染时附加#search_hint
的同一帧。 To mitigate this you could wait for the frame to render, and then add/remove the class. 为了减轻这种情况,您可以等待框架渲染,然后添加/删除类。 I've done this using
setTimeout
with timeout value zero. 我使用超时值为零的
setTimeout
完成了此操作。
const searchHint = ` <h3 id="search_hint" class="invizible"> Enter a search term to continue! </h3> `; $('#search_label').append(searchHint); setTimeout(function() { $('#search_hint').removeClass('invizible').addClass('make_vizible'); },0);
#search_hint { color: white; transition: color 1s ease; } #search_hint.invizible { color: white; } #search_hint.make_vizible { color: #404040; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="search_label"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.