如果'image-reveal-check'的父级有一个活动的类,我需要向img
元素添加一个类(用于动画),该怎么做?
说明:父类并不总是具有“活动”状态,该类是在元素进入视口时添加的。
HTML
<div class="active">
<div class="image-reveal-check">
<div class="image-reveal-inner">
<img>
</div>
</div>
</div>
jQuery
if ($(".image-reveal-check").parent().hasClass('active')) {
$(".image-reveal-inner img").addClass('image-reveal-start');
}
答案 0 :(得分:1)
尝试使用此功能。您可以在代码段中检查输出。
$( document ).ready(function() {
console.log( "ready!" );
if ($(".image-reveal-inner").parent().hasClass('image-reveal-check')) {
$(".image-reveal-inner img").addClass('image-reveal-start-add');
console.log( "done!" );
}
});
<div class="active">
<div class="image-reveal-check">
<div class="image-reveal-inner">
ASD
<img alt="img title">
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
答案 1 :(得分:1)
当active
类添加到div
时,您可以显式触发事件。
在这里,我添加了一个按钮,您可以在将元素添加到视口时进行操作。
$("#addClassActive").click(function() {
//Here on button click the active class is added to div. For your case this needs to be called when the element added to the viewport
$('.image-reveal-check').parent().addClass('active').trigger('classChange');
});
$('div:eq(0)').on('classChange', function() { //finding the root div and finding img and adding the desired class
$(this).find("img").addClass("image-reveal-start")
});
.image-reveal-start
{
border: solid 1px red;
width: 50px;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="image-reveal-check">
<div class="image-reveal-inner">
<img src="#" title="I am Image!" alt="I am Image!" />
<button id="addClassActive">Add Class</button>
</div>
</div>
</div>
答案 2 :(得分:0)
您可以完全不使用JS来实现,只需在CSS代码中添加一条规则即可:
div.active .image-reveal-inner img { }
下面的示例显示如何使用规则对具有父类active
的第一张图像进行动画处理,而不是如何对父类active
上没有div
类的第二张图像进行动画处理。
div.active .image-reveal-inner img {
position: relative;
-webkit-animation: floatBubble 2s normal ease-out;
animation: floatBubble 2s normal ease-out;
}
@-webkit-keyframes floatBubble {
0% {
right: 300px;
}
100% {
right: 0px;
}
}
@keyframes floatBubble {
0% {
right: 300px;
}
100% {
right: 0px;
}
}
<div class="active">
<div class="image-reveal-check">
<div class="image-reveal-inner">
<img alt="img title" src="https://i.stack.imgur.com/2lRQ9.png">
</div>
</div>
</div>
<div>
<div class="image-reveal-check">
<div class="image-reveal-inner">
<img alt="img title" src="https://i.stack.imgur.com/2lRQ9.png">
</div>
</div>
</div>