无法通过使用jQuery切换类来触发转换 [英] Can't trigger transition by toggling classes with jQuery

查看:65
本文介绍了无法通过使用jQuery切换类来触发转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个简单的过渡,但是很难用jQuery做这件事。
我在eventListener中创建要在JS中转换的元素,如下所示:

I want to make a simple transition but struggle doing it with jQuery. I create the element that is to be transformed in JS in an eventListener like so:

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')

在我的样式表中,我为类'invizible'和'make_vizible'提供了这些样式:

In my stylesheet I've got those styles for the classes 'invizible' and 'make_vizible':

#search_hint.invizible {
  color: white;
  transition: color 1s ease;
}

#search_hint.make_vizible {
  color: #404040;
}

据我所知,这会导致搜索提示元素慢慢淡入。我使用invizible类创建它,其中存在transition属性,还有要转换的属性的起始值。然后我将类切换到具有不同颜色值的类。

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.

任何想法?

推荐答案

有两个问题:


  1. 转换属性在 invizible 类中设置。因此,一旦删除它,该属性就不适用。要解决此问题,请将转换与元素ID相关联。

  1. The transition property is set in invizible class. So once you remove it, that property is not applicable. To resolve this, associate the transition to the element id.

removeClass addClass 可能会应用于渲染时追加 #search_hint 的同一帧。要缓解这种情况,您可以等待帧渲染,然后添加/删除该类。我已经使用 setTimeout 完成了此操作,超时值为零。

The removeClass and addClass are probably getting applied to the same frame that appends #search_hint while rendering. 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.

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>

这篇关于无法通过使用jQuery切换类来触发转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆