【问题标题】:Bootstrap - Jumbotron - Automatic image change - jQueryBootstrap - Jumbotron - 自动图像更改 - jQuery
【发布时间】:2026-01-10 13:05:02
【问题描述】:

我正在使用 Bootstrap Jumbotron 并尝试创建一个 jQuery 函数,该函数会自动循环浏览 img 文件夹中的不同图像;目前只有三个slider#.jpg img,预期的行为是2秒后css中的img被slider2.jpg替换,依此类推,直到它返回slider1.jpg。问题是这没有发生,并且图像不会从滑块 1 变为 2 或 3。

这是我的 HTML:

    <div class="jumbotron">
        <div class="container">
            <div class="row">
                <div class="col-md-6 jumbotron-text">
                    <h1>CAMD</h1>
                    <p>Soluciones integrales para el hogar</p>
                    <a href="contact.html" class="btn btn-contact" role="button">CONTACTO</a> 
                </div>
            </div>
        </div>          
    </div> 

这是 CSS:

.jumbotron {
    margin-bottom: 0px;
    background-image: url(../img/slider1.jpg);
    background-position: 0% 25%;
    background-size: cover;
    background-repeat: no-repeat;
    height: 500px;
}

这是 jQuery:

$(document).ready(function() {
    var imgId = 0
    var numberOfImages = 3;
    setInterval(function() {
    $(".jumbotron").css('background-image','url('../img/slider' + 'imgId' + '.jpg')');;
    imgId = (imgId + 1) % numberOfImages;
  }, 2000);
});

【问题讨论】:

    标签: javascript jquery html css twitter-bootstrap


    【解决方案1】:

    您还没有说明您的问题或错误是什么......但是,乍一看,这行看起来是错误的:

    $(".jumbotron").setInterval(function() {
    

    setInterval 函数不是可以在选定元素上调用的 jQuery 函数。这是window 上的一个功能。我认为这条线应该是:

    setInterval(function() {
    

    window.setInterval(function() {
    

    其次,这不是有效的代码:

    $(".jumbotron").css('background-image','url('../img/slider' + 'imgId' + '.jpg')');;
    

    引号不正确,您尝试添加文字字符串 'imgId' 而不是变量的值。你可能想要:

    $(".jumbotron").css('background-image','url("../img/slider' + imgId + '.jpg")');
    

    【讨论】:

    • 我已经根据您的反馈更新了问题并重新配置了 jQuery,但它仍然没有循环浏览各种图像。
    • 我为我的答案添加了更新。您的字符串生成代码不正确。
    最近更新 更多