简体   繁体   English

jQuery:等待CSS动画完成,然后再更改另一个CSS属性

[英]jQuery: wait for css animation to complete before changing another css attribute

I have a stack of images, absolutely positioned on the same place and I only have one image visible at a time by setting zIndex=-1 for all images but the visible one. 我有一堆图像,它们绝对位于同一位置,并且通过对所有图像(除了可见图像)设置zIndex = -1一次只能看到一个图像。 On another side of the page I have a list of all the image names and when I hover on a specific image name I want that image to become visible by fading in and the previously visible one to fade out. 在页面的另一侧,我列出了所有图像名称,当我将鼠标悬停在特定的图像名称上时,我希望该图像通过淡入变得可见,而以前可见的图像则逐渐消失。 I do this with this code 我用这段代码

$(this).hover(  //visible and hover below are variable names  
        visible.css({opacity: '0',zIndex: '-1'}); //the previous image diassapears
        hovered.css({ zIndex: '1', opacity: '1'}); //the new image fades in
    )

and by transitioning the opacity property through css. 并通过CSS转换不透明度属性。 The problem is that when I hover over a new image name, the old image just disappears without fading out and the new one starts to fade in. I suppose that the old image does indeed fade out, yet it does so in the background due to zIndex=-1 becoming immediately effective. 问题是,当我将鼠标悬停在新的图像名称上时,旧图像会消失而不会褪色,而新图像会逐渐淡入。我想旧图像确实会逐渐淡出,但由于zIndex = -1立即生效。 I would like to ask the best way to solve this. 我想问一下解决这个问题的最佳方法。 Please, notice that I want to do this without using jQuery animations and only using pure css animations just to take advantage of the (minimally) higher speed of css animations. 请注意,我想这样做而不使用jQuery动画,而仅使用纯CSS动画只是为了利用(最低)较高的CSS动画速度。 So a solution that puts almost no computational overhead (so that a css animation in this case still remains advantageous) would be preferable. 因此,几乎没有计算开销的解决方案(因此在这种情况下,css动画仍然保持优势)将是更好的选择。

You need to apply the z-index:-1 after it has animated back to opacity 0, otherwise it is just "popping" below without showing the opacity change. 在将z-index:-1动画化为不透明度0之后,您需要应用z-index:-1 ,否则它只是在下面“弹出”而没有显示不透明度变化。

You need to trigger on a transitionEnd event. 您需要在transitionEnd事件上触发。 See this SO post about normalizing that event for all browsers. 请参阅这篇SO帖子,了解如何为所有浏览器标准化该事件。

But once you work that out, its basically just attaching a one off event with the callback setting the final z-index - something like this: 但是一旦解决了这个问题,它基本上只是将一个off事件与回调一起设置最终的z-index,如下所示:

visible.one('transitionEnd', function(){
    visible.css('z-index', -1);
}).css( 'opacity', 0 );

You just need to use the script in the other SO post to get your normalized 'transitionEnd' event. 您只需要在其他SO帖子中使用脚本即可获取标准化的'transitionEnd'事件。

Hope this helps! 希望这可以帮助!

use animate - it comes with queue management and callback support "out of the box" 使用animate -它带有“开箱即用”的队列管理和回调支持

http://api.jquery.com/animate/ http://api.jquery.com/animate/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM