给定一系列图像替换背景图像

时间:2017-01-12 01:16:48

标签: javascript jquery css

我正在尝试为已经包含图片的div设置背景图片旋转,似乎没有任何改变,我想我会检查是否有人可以看到问题,因为没有出现错误。

 <script>
    $( document ).ready(function() {
        setInterval(function() {
        var tips = [
        "header.jpg",
        "header2.jpg",
        "header3.jpg",
        "header4.jpg",
        "header5.jpg",

        ];
        var i = 0;
         if (i == tips.length) --i;
    $('.containercoloring').fadeTo('slow', 0.3, function()
    {
        $(this).css('background-image', 'url(' + tips[i] + ')');
    }).delay(1000).fadeTo('slow', 1);
    i++;
    }, 5 * 1000);
    });
    </script>
    <body>
    <div class="containercoloring"> </div>
    </body>

2 个答案:

答案 0 :(得分:0)

以下是工作(更新)代码。我希望你单独导入jquery lib。

<script>
    $(document).ready(function() {
        var i = 0;
        setInterval(function() {
            var tips = [
                "header.jpg",
                "header2.jpg",
                "header3.jpg",
                "header4.jpg",
                "header5.jpg"
            ];
            var imageIndex = ++i % tips.length;
            $('.containercoloring').fadeTo('slow', 0.3, function() {
                $(this).css('background-image', 'url(' + tips[imageIndex] + ')');
            }).delay(1000).fadeTo('slow', 1);
        }, 5 * 1000);
    });
</script>

<body>
    <div class="containercoloring" style="height: 100px;">Image Container</div>
</body>

您可以在此jsfiddle中进行测试 - https://jsfiddle.net/nbq9f6bg/

希望它有所帮助!

答案 1 :(得分:0)

所以我有一些关于你的例子的笔记。请参阅下面的评论。我使用了背景颜色并删除了过渡以更容易显示。

// declare variables
var tips = [
  "#ff9000",
  "#ff0000",
  "#0099ff"
];

// counter
var i = 0;

// direction
var direction = 'forwards';

// time in between intervals
var timer = 2000;

function changeBackground() {
  // Check the length minus 1 since your counter starts at 0
  if (i == (tips.length - 1)) {
    direction = 'backwards';
  } else if(i == 0) {
    // only set the direction back to forwards when the counter is 0 again
    direction = 'forwards';
  }
  $('.containercoloring').css('background-color', tips[i]); 
    
  // add or subtract based on the direction 
  if(direction == 'forwards') {
    i++;
  } else {
    i--;
  }
}


$( document ).ready(function() {
  // save interval to a variable so you can stop it later
  var theInterval = setInterval(changeBackground, timer);
  
  // run the function since the interval will take 2000ms to execute
  changeBackground();
});
.containercoloring {
  height: 100px;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="containercoloring"> </div>