无限循环一组图像

infinite loop a set of images

本文关键字:一组 图像 无限循环      更新时间:2023-09-26

当它到达最后一个图像时,效果不太好,我必须单击两次才能返回到第一个图像。

var i = 1;
$('.rightArrow').click(function () {
    if(i != 4) {
        $('body').css(
            'background',
            'linear-gradient(rgba(0, 0, 0, 0.30),rgba(0, 0, 0, 0.30)), url("'+
                customerBgs[i]+'") no-repeat center center fixed'
        );
        i++;
    }else{
        i = 0;
        $('body').css(
            'background',
            'linear-gradient(rgba(0, 0, 0, 0.30),rgba(0, 0, 0, 0.30)), url("'+
                customerBgs[i]+'") no-repeat center center fixed'
        );
    }
});

为什么不做更简单的

var i = 0;
var customerBgs = ['http://placehold.it/350x150', 'http://placehold.it/500x100', 'http://placehold.it/100x510', 'http://placehold.it/300x500'];
$('.rightArrow').click(function() {
    $('body').css(
        'background',
        'linear-gradient(rgba(0, 0, 0, 0.30),rgba(0, 0, 0, 0.30)), url("' + customerBgs[i] + '") no-repeat center center fixed');
    i = ++i % customerBgs.length;
});

下方的演示

var i = 0;
var customerBgs = ['http://placehold.it/350x150', 'http://placehold.it/500x100', 'http://placehold.it/100x510', 'http://placehold.it/300x500'];
$('.rightArrow').click(function () {
    $('body').css(
        'background',
        'linear-gradient(rgba(0, 0, 0, 0.30),rgba(0, 0, 0, 0.30)), url("' + customerBgs[i] + '") no-repeat center center fixed');
    i = ++i % customerBgs.length;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input class="rightArrow" type="button" value="right" />

我假设customerBgs从0 开始

var i = 0;
$('.rightArrow').click(function(){
    i++;
    if (i > customerBgs.length - 1) {
        i = 0;
    }
    $('body').css(
        'background',
        'linear-gradient(rgba(0, 0, 0, 0.30),rgba(0, 0, 0, 0.30)), url("'+
            customerBgs[i]+'") no-repeat center center fixed'
    );
});

您没有在else块中递增i,因此它重置为图像0,然后在转到图像1之前再次设置背景。然而,您可能会将递增从if情况中提取出来,然后在设置背景之前检查是否需要换行为0。这将使您不必在两个块中重复背景设置。