如何使用淡入 css 属性 更改 jquery

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)')
})

但是我想让它淡入所以我试了这个:

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

还有这个

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

但两者都不行。这是一个 fiddle

有什么想法吗?

尝试将 display 属性 设置为 none 一开始,

JS:

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

CSS:

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

从技术上讲,fadeIn() 不会对已经可见的元素进行动画处理(淡入)。此外,我们不应将 display 属性 与 visible 属性 混淆。即使 visible 属性 设置为 hidden fadeIn 也不会起作用。 display : none.fadeIn()

的有效值

DEMO

fadeIn() 适用于隐藏元素,因此您可以使用 hide() 隐藏您的 box 然后 fadein 将起作用:

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

希望对您有所帮助。