jquery将类添加到background-image

时间:2018-05-21 08:56:16

标签: jquery animate.css

我想使用animate.css为div的背景图像设置动画(例如应用脉冲效果)。我必须将所需的动画类添加到我想要以下列格式进行动画处理的任何元素:

<img class="animated infinite pulse">

现在我的问题是如何将这些类添加到div中的背景图像?我尝试使用jquery选择背景图像并向其添加类但出现错误:

var psd = $('#mydiv').css('background-image');
$(psd).addClass("animated infinite pulse");

或其他代码:

$('#mydiv').filter(function() {
    return $(this).css("background-image"); 
}).addClass('animated infinite pulse');

最后一个代码将动画类添加到整个div并使整个div动画化。请帮助解决这个问题。

1 个答案:

答案 0 :(得分:1)

您应addClass()加上background-image而非css属性的元素。

&#13;
&#13;
var psd = $('#mydiv'); // This has background image already
$(psd).addClass("animated infinite pulse");
&#13;
#mydiv {
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg');
  width: 300px;
  height: 300px;
  background-size: cover;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css" />
<div id="mydiv"></div>
&#13;
&#13;
&#13;

或修复background-image

&#13;
&#13;
var psd = $('#mydiv'); // This has background image already
$(psd).addClass("animated infinite pulse");
&#13;
#mydiv {
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg');
  width: 300px;
  height: 300px;
  background-size: cover;
}

#parent {
  width: 300px;
  height: 300px;
  overflow: hidden;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css" />
<div id="parent">
  <div id="mydiv"></div>
</div>
&#13;
&#13;
&#13;