循环css背景通过JavaScript无法在codepen中工作

时间:2016-01-29 16:21:35

标签: javascript css loops

我需要循环通过css background-image

有没有人在这里看到为什么背景没有改变:http://codepen.io/anon/pen/dGKYaJ

var bg = $('.background').css('background-image');
bg = bg.replace('url(','').replace(')','');
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = bg;
backgrounds[1] = 'https://placehold.it/300x300&text=1';
backgrounds[2] = 'https://placehold.it/300x300&text=2';

function changeBackground() {
    currentBackground++;
    if(currentBackground > 2) currentBackground = 0;

    $('.background').fadeOut(3000,function() {
        $('.background').css({
            'background-image' : "url('" + backgrounds[currentBackground] + "')"
        });
        $('.background').fadeIn(3000);
    });


    setTimeout(changeBackground, 7000);
}

$(document).ready(function() {
    setTimeout(changeBackground, 7000);        
});

任何建议都表示赞赏

RA

1 个答案:

答案 0 :(得分:0)

  1. 在控制台中抛出此错误:

    Uncaught ReferenceError: $ is not defined
    

    您忘了将jQuery librery包含在codpen设置中。校验 this working codepen

  2. 第2行要解决的另一个问题是:bg = bg.replace('url(','').replace(')','');需要替换为:

    bg = bg.replace('url(\"','').replace('\")','');
    

    否则背景[0] 值将被双引号 ""https://...""在尝试加载时出现404错误 图像。

  3. var bg = $('.background').css('background-image');
    bg = bg.replace('url(\"','').replace('\")','');
    var currentBackground = 0;
    var backgrounds = [];
    backgrounds[0] = String(bg);
    backgrounds[1] = 'https://placehold.it/300x300&text=1';
    backgrounds[2] = 'https://placehold.it/300x300&text=2';
    
    
    function changeBackground() {
        currentBackground++;
        if(currentBackground > 2) currentBackground = 0;
    
        $('.background').fadeOut(3000,function() {
    
            $('.background').css({
                'background-image' : "url('" + backgrounds[currentBackground] + "')"
            });
            $('.background').fadeIn(3000);
        });
    
    
        setTimeout(changeBackground, 7000);
    }
    
    $(document).ready(function() {
        setTimeout(changeBackground, 7000);        
    });
    .background
    {
      background-image:url("https://placehold.it/300x300&text=original");
      height:300px;
      width:300px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="background"></div>