从底部到顶部动画背景图像,连续重复jQuery

时间:2015-09-30 21:43:57

标签: jquery html css jquery-animate

当您登陆页面时,我希望背景图像聚焦在图像的底部,然后平移到图像的顶部,然后向下返回并不断重复。我有以下代码:

<body>
    <div id="container"></div>
</body>

body {
    height: 100%;
    background-image: url(http://smmcnyc.com/work/apf/wp2/wp-content/uploads/2015/09/front-img2.jpg);
    background-repeat: no-repeat;
    background-position: 50% 100%;
    background-attachment: fixed;
}
#container {
    height: 100vh;
}

$(document).ready(function () {
    $('body').animate({
        'background-position-x': '50%',
        'background-position-y': '0'
    }, {
        duration: 500,
    });
});    

为什么这不起作用?如何让过程连续循环上下?我是否可以使用此代码,因为Firefox不支持“background-position-x”,但jQuery不支持.animate()支持“background-position”?

JSFiddle在这里:https://jsfiddle.net/bqc8o2hn/2/

2 个答案:

答案 0 :(得分:2)

这是你想要的吗?我是用css过渡做的。

<body>
    <div id="container"></div>
</body>


$(document).ready(function () {
    $("body").toggleClass("to_top");
    window.setInterval(function(){
    $("body").toggleClass("to_top");
    },4000);
});    

body {
    height: 100%;
    background-image: url(http://smmcnyc.com/work/apf/wp2/wp-content/uploads/2015/09/front-img2.jpg);
    background-repeat: no-repeat;
    background-position: 50% 100%;
    background-attachment: fixed;
    transition:all 2s;
}
#container {
    height: 100vh;
}
.to_top{
    background-position: 50% 0%;
}

答案 1 :(得分:1)

请查看更新后的fiddle

body {
    height: 100%;
    background-image: url(http://smmcnyc.com/work/apf/wp2/wp-content/uploads/2015/09/front-img2.jpg);
    background-repeat: no-repeat;
    background-position: 50% 100%;
    background-attachment: fixed;
}
body.loaded {
    animation: bouncebg 5s ease;
}
@keyframes bouncebg {
    0%, 100% {
        background-position: 50% 100%;
    }
    50% {
        background-position: 50% 0;
    }
}
@-webkit-keyframes bouncebg {
    0%, 100% {
        background-position: 50% 100%;
    }
    50% {
        background-position: 50% 0;
    }
}
@-moz-keyframes bouncebg {
    0%, 100% {
        background-position: 50% 100%;
    }
    50% {
        background-position: 50% 0;
    }
}
#container {
    height: 100vh;
}

更新了JS代码

$(document).ready(function () {
    setTimeout(function(){
        $('body').addClass('loaded');
    }, 1000);
});    

希望,这会有所帮助!