[英]Jquery .addClass() prevents css transition
In working to transition an image from grayscale to full color after a fixed time I encountered a problem with Jquery's interaction with CSS Transition and i'm not sure what the work around is supposed to be: 在固定时间后将图像从灰度转换为全彩色的过程中,我遇到了Jquery与CSS Transition交互的问题,我不确定应该如何解决:
If I start out with the existing #globecont img {
style and change the .globefc
from a class to a #globefc:hover
everything works fine. 如果我从现有的
#globecont img {
样式开始,然后将.globefc
从类更改为#globefc:hover
一切正常。 But when I use Jquery to apply it as a class after a delay - the "class" is added to the IMG properly, but no transition or change in the filter is occurring. 但是,当我在延迟后使用Jquery将其作为类应用时-“类”已正确添加到IMG,但是过滤器中没有发生过渡或更改。
I have not yet tried using .trigger("hover") in place of .addClass() but regardless of if that works or not, can someone explain why this doesn't work as written? 我还没有尝试使用.trigger(“ hover”)代替.addClass(),但是不管是否可行,有人可以解释为什么这不能按书面要求进行吗?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
body {background-color:#000000;}
#globecont {position:relative; margin-left:auto; margin-right:auto; text-align:center;}
#globecont img {
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
transition: 3s;
}
.globefc {
filter: grayscale(0%);
-webkit-filter: grayscale(0%);
filter: none;
}
</style>
</head>
<body>
<div id="globecont"><img src="http://philanthropicsandbox.org/wp-content/uploads/2012/12/Globe1.png" width="300" height="300" id="globe"></div>
<script>
$(document).ready(function() {
$('#globe').delay(500).addClass("globefc");
});
</script>
</body>
</html>
The problem is, #globecont img
is a more specific selector then .globefc
, meaning it overrides the style added by .globefc
, even though it is further down the stylesheet. 问题是,
#globecont img
是一个比.globefc
更具体的选择器,这意味着它覆盖了.globefc
添加的.globefc
,即使它在样式表的下方。
You can fix this by making the second selector more specific: 您可以通过使第二个选择器更具体来解决此问题:
#globe.globefc {
filter: grayscale(0%);
-webkit-filter: grayscale(0%);
filter: none;
}
Note: In your html, you already had the class .globefc
added to the image, so the jQuery didn't actually do anything. 注意:在html中,您已经在图像中添加了
.globefc
类,因此jQuery实际上并未执行任何操作。 In the JSFiddle, I removed that class, since it is added 500ms later by the jQuery. 在JSFiddle中,我删除了该类,因为jQuery在500ms之后添加了该类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.