gpt4 book ai didi

javascript - 通过javascript循环css背景在codepen中不起作用

转载 作者:行者123 更新时间:2023-11-28 06:29:15 24 4
gpt4 key购买 nike

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

感谢任何建议

最佳答案

  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://..."" 在尝试加载时引发 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>

关于javascript - 通过javascript循环css背景在codepen中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35089194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com