我需要循环通过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
答案 0 :(得分:0)
在控制台中抛出此错误:
Uncaught ReferenceError: $ is not defined
您忘了将jQuery librery包含在codpen设置中。校验 this working codepen
第2行要解决的另一个问题是:bg =
bg.replace('url(','').replace(')','');
需要替换为:
bg = bg.replace('url(\"','').replace('\")','');
否则背景[0] 值将被双引号
""https://...""
在尝试加载时出现404错误
图像。
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>