1

I have the following piece of JS which toggles the BG color from red to green and so on.

function blink() {
            var currentColor = 'red';
            setInterval(function () {
                document.body.style.backgroundColor = currentColor;
                currentColor = currentColor === 'red' ? 'green' : 'red';
            }, 1000);
        };

Is there anyway to change the colours to images so it toggles between two images instead of two colours?

I have tried the following but without success:

function toggleBG() {
            var currentColor = "Images/tableBGRed.gif";
            setInterval(function () {
                var myDiv = document.getElementById("testDiv");
                myDiv.style.backgroundImage = "url('" + currentColor + "')";
                currentColor = currentColor === "url('Images/tableBGRed.gif')" ? "url('Images/tableBG.gif')" : "url('Images/tableBGRed.gif')";
            }, 1000);
        };

Something wrong with the syntax?

4

2 に答える 2

2
currentColor = currentColor === "url('Images/tableBGRed.gif')" ? "url('Images/tableBG.gif')" : "url('Images/tableBGRed.gif')"; 

文字列が のようなものになりますが"url(url(' Images/cat.gif '))"、これは の有効な値ではありません myDiv.style.backgroundImage

myDiv.style.backgroundImage = "url('" + currentColor + "')";前の行にあるので。

アップデート:

CSS3 を使用して、アニメーション (フェード) のように見せることができます。

#testDiv{
-webkit-transition: all 0.1s ease;
-moz-transition: all 0.1s ease;
-ms-transition: all 0.1s ease;
-o-transition: all 0.1s ease;
transition: all 0.1s ease;
}
于 2013-09-27T12:19:58.950 に答える
1

私には、あなたのコードは backgroundimage を次のように作成しているようです

url('url('Images/xxx.gif')')

試す

function toggleBG() {
    var currentColor = "url('Images/tableBGRed.gif')";
    setInterval(function () {
        var myDiv = document.getElementById("testDiv");
        myDiv.style.backgroundImage = currentColor;
        currentColor = currentColor === "url('Images/tableBGRed.gif')" ? "url('Images/tableBG.gif')" : "url('Images/tableBGRed.gif')";
    }, 1000);
};
于 2013-09-27T12:20:49.897 に答える