CSS后台更改之间的延迟

时间:2015-11-22 12:33:04

标签: jquery css

我试图通过在函数上调用UPDATE sportsclub SET '"Column_name"' = '"New_value"' WHERE club_id = '"Condition"' 来旋转CSS背景,但代码并没有按预期工作。只有一个过渡,然后它立即跳到最后一个图像。

JsFiddle

setTimeout

由于

4 个答案:

答案 0 :(得分:2)

你可以不用很多setTimeouts,尝试这样的事情:

var func = function () {
    var images = [
        'http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/diamond_upholstery.png',
        'http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/subtle_stripes.png',
        'http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/struckaxiom.png',
        'http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/dark_stripes.png'
    ]; 
    var state = $('#rotator').data('background-image-state');
    var newState = state % images.length;
    $('#rotator').data('background-image-state', newState);
    $('#rotator').css("background-image", "url("+images[newState]+")");

    setTimeout(func, 2000);

}
$('#rotator').data('background-image-state', 0);
setTimeout(func, 0);

答案 1 :(得分:2)

您可以使用setInterval代替setTimeout



var i = 0;
var rotator = document.querySelector('#rotator');
var path = 'http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/';

var backgrounds = [
'diamond_upholstery',
'subtle_stripes',
'struckaxiom',
'dark_stripes'
];

function func(i) {
setInterval(function(){
if (i === (backgrounds.length-1)) {i = 0;} else {i++;}
rotator.style.backgroundImage = 'url(' + path + backgrounds[i] + '.png)';}, 2000);
}

window.onload = func(i);

#rotator {
width: 160px;
height: 160px;
background-image:url('http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/diamond_upholstery.png');
}

<div id="rotator">
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

将超时的持续时间更改为不同,现在它们都会同时结束(2000毫秒)。如果您希望每个都是2000毫秒的一部分,请将它们2000400060008000

答案 3 :(得分:1)

您应该使用回调函数。以下是Fiddle描述的相同内容。

代码

function updateImage(url, callback) {
    var _url = 'http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/';
    _url += url;
    $('#rotator').css("background-image", "url(" + _url + ")");
    setTimeout(function () {
        callback();
    }, 2000);
}

var func = function () {
    updateImage("diamond_upholstery.png",
    function () {
        updateImage("subtle_stripes.png",
        function () {
            updateImage("struckaxiom.png",
            function () {
            	updateImage("dark_stripes.png",
                           function(){})
            });
        })
    });
}
setTimeout(func, 2000);
#rotator {
    width: 200px;
    height: 200px;
    display: block;
    background-image: url(http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/diagmonds.png);
    transition: background 0.5s linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rotator"></div>