从我的Div background-image属性循环3图像

时间:2016-02-20 14:28:31

标签: javascript jquery html css

我有一个代码来循环图像但基于Img源,但是如何改进它以使其适用于" background-image" div的财产?

HTML

<div id="section2"></div>   

CSS

#section2 {
background-image: 'url(..images/banner1.jpg');
} 

JAVASCRIPT

<script type = "text/javascript">
(function() {     
var i = 1;
var pics = [ "images/banner1.jpg", "images/banner2.jpg", "images/banner3.jpg" ];
var el = document.getElementById('section2');  
function toggle() {
    el.src = pics[i];           
    i = (i + 1) % pics.length;  
}
setInterval(toggle, 3000);
})();             
  </script>

提前致谢:)

1 个答案:

答案 0 :(得分:1)

一种方法是使用CSS类而不是源代码。

<强> JS:

<script type = "text/javascript">
(function() {     
var i = 1;
var classes = [ "bgd-1", "bgd-2", "bgd-3" ]; // adjusted
var el = document.getElementById('section2');  
function toggle() {
    el.className = classes[i]; // adjusted           
    i = (i + 1) % classes.length; // adjusted 
}
setInterval(toggle, 3000);
})();             
</script>

<强> CSS:

#section2.bgd-1 {
    background-image: url('..images/banner1.jpg');
} 

#section2.bgd-2 {
    background-image: url('..images/banner2.jpg');
} 

#section2.bgd-3 {
    background-image: url('..images/banner3.jpg');
} 

注意:

使用el.className += ' ' + classes[i];附加类名而不是替换所有元素类。