CSS3替代jQuery.fadeIn和fadeOut [英] CSS3 replacement for jQuery.fadeIn and fadeOut
问题描述
我编写了少量代码,尝试使用CSS过渡来复制jQuery的.fadeIn()
和.fadeOut()
函数,以使其在触摸设备上看起来更好.
I have written a small amount of code to try and replicate jQuery's .fadeIn()
and .fadeOut()
functions using CSS transitions to look better on touch devices.
理想情况下,我想避免使用库,这样我就可以准确地编写自己想要的东西,并作为学习练习.
Ideally I'd like to avoid using a library so that I can write exactly what I want, and as a learning exercise.
fadeOut
效果很好.
fadeIn
的想法是使用CSS3过渡来调整元素的不透明度,然后将元素设置为display:block;
(使用is-hidden
类),以确保它仍然不可单击或覆盖下面的内容它.
The idea for fadeIn
is to use CSS3 transitions to adjust the opacity of an element, after which the element will be set to display:block;
(using is-hidden
class) to ensure it's not still clickable or covering something beneath it.
fadeIn
无效.我认为这是由于在删除is-hiding
类的同时添加了is-animating
类.由于不会发生过渡,因此永远不会触发transitionEnd事件:
fadeIn
is not working though. I think it is due to adding the is-animating
class at the same time as removing the is-hiding
class. The transitionEnd event never fires because a transition does not occur:
function fadeIn (elem, fn) {
var $elem = $(elem);
$elem.addClass('is-animating');
$elem.removeClass('is-hidden');
$elem.removeClass('is-hiding');
$elem.on(transitionEndEvent, function () {
$elem.removeClass('is-animating');
if (typeof fn === 'function') {
fn();
}
});
};
和CSS
.is-animating {
@include transition(all 2000ms);
}
.is-hiding {
// Will transition
@include opacity(0);
}
.is-hidden {
// Won't transition
display: none;
}
代码如下: CodePen链接
Update: I have found what I'd describe as a hack, but that works very well: CSS3 replacement for jQuery.fadeIn and fadeOut
此修复程序后的工作代码:已修复
Working code after this fix: Fixed
但是没有setTimeout
的解决方案将非常有价值.
A solution without setTimeout
would be very valuable though.
推荐答案
我已经设法通过做一些不自然和骇人听闻的事情来解决此问题:
I have managed to fix this by doing something that feels unnatural and hacky:
function fadeIn (elem, fn) {
var $elem = $(elem);
$elem.addClass('is-animating');
$elem.removeClass('is-hidden');
// Smelly, setTimeout fix
setTimeout(function () {
$elem.removeClass('is-hiding');
}, 0);
$elem.on(transitionEndEvent, function () {
$elem.removeClass('is-animating');
if (typeof fn === 'function') {
fn();
}
});
};
将setTimeout
函数添加到包含可转换属性的类中,即可解决此问题.
Adding the setTimeout
function to the class that contains the transition-able property fixes the issue.
此处的工作代码: Codepen固定代码
这篇关于CSS3替代jQuery.fadeIn和fadeOut的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!