【问题标题】:Loop css background via javascript not working in codepen通过javascript循环css背景在codepen中不起作用
【发布时间】:2016-01-29 16:21:35
【问题描述】:

我需要遍历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);        
});

欢迎提出任何建议

【问题讨论】:

标签: javascript css loops


【解决方案1】:
  1. 此错误在控制台中抛出:

    Uncaught ReferenceError: $ is not defined
    

    您忘记将 jQuery 库包含到 codpen 设置中。查看 this working codepen.

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

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

    否则 backgrounds[0] 值将被双引号 ""https://..."" 在尝试加载 图片。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2016-02-22
    • 1970-01-01
    • 2020-10-25
    • 2013-07-30
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多