简体   繁体   中英

How can I animate or transition CSS when a class is added with jquery

I've tried multiple examples but for some reason my CSS just won't animate. CSS keyframes worked but I am adding and removing a class to resize a logo when scrolling down. With keyframes it resizes to a smaller logo when scrolling down, but jumps immediately back to big when scrolling back up again.

This is my code:

Logo html:

<div class="col-lg-3 col-md-2 col-sm-6 col-xs-5">
    <a class="logolink" href="#"><img src="asset/img/logo-white.png" alt=""></a>
</div>

My jQuery:

if ($(this).scrollTop() > 50) {
    $('.logolink img').addClass('logo-small');
} else {
    $('.logolink img').removeClass('logo-small');
}

And my CSS:

.logolink{
  position: relative;
  display: inline-block;
}

.logo-small{
  max-height:100px;
}

I've tried adding transition: height 2s; or transition: max-height 2s; to .logo-small but this doesn't work. What is the correct way to do this?

Is this what you trying to do?

 $(document).on("scroll",function(){ if ($(this).scrollTop() > 50) { $('.logolink img').addClass('logo-small'); } else { $('.logolink img').removeClass('logo-small'); } });
 body{ height:200vh; }.logolink{ position: fixed; top:0; }.logolink img{ height:300px; transition-duration:0.5s; }.logo-small{ height:100px;important; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col-lg-3 col-md-2 col-sm-6 col-xs-5"> <a class="logolink" href="#"><img src="https://picsum.photos/id/237/200/300" alt=""></a> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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