简体   繁体   中英

How to use fadeIn with css property change jquery

HTML :

<input id ="input"/>
<div id="box"></div>

CSS :

#box{
   width: 100px;
   height: 100px; 
}

JS :

$('#input').on('focus',function(){
    $("#box").css('background', 'linear-gradient(red, transparent)')
})

However I want it to fade in so I tried this:

$("#box").css('background', 'linear-gradient(red, transparent)').fadeIn(1500);

And also this

$('#input').on('focus',function(){
  $("#box").fadeIn(1500, function(){
    $("#box").css('background', 'linear-gradient(red, transparent)');
  });
})

But both don't work. Here's a fiddle

Any ideas?

Try to set display property as none initially,

JS:

$('#input').on('focus',function(){
  $("#box").css('background', 'linear-gradient(red, transparent)').fadeIn(1500);
});

CSS:

#box{
  width: 100px;
  height: 100px;
  display:none;
}

Technically, fadeIn() will not animate(fade in) an element which is already visible. Also we should not confuse display property with visible property. Even if visible property is set with hidden fadeIn will not work. display : none is the valid one for .fadeIn()

DEMO

The fadeIn() works on hidden elements so you could hide your box using hide() then fadein will works :

$('#input').on('focus',function(){
  $("#box").hide().css('background', 'linear-gradient(red, transparent)').fadeIn(1500);
})

Hope this helps.


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