1

次のコードを使用して、ページが更新されたときに背景画像を変更しています

function changeImg(imgNumber) {
    var myImages = ["../img/background_tile.png", "../img/background_tile_blue.png", "../img/background_tile_green.png", "../img/background_tile_purple.png"]; 
    var newImgNumber =Math.floor(Math.random()*myImages.length);
    document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;

background-color今、CSSを画像の色に変更して、ページが更新されたときにページが読み込まれる前に白く点滅しないようにしようとしています。

ウェブサイト - http://lauramccartney.co.uk

編集 - 私はみんなそれを解決しました! 私はこれを使いました

function changeImg(imgNumber) {
    var myImages = ["../img/background_tile.png", "../img/background_tile_blue.png", "../img/background_tile_green.png", "../img/background_tile_purple.png"]; 
    var myColors = ["#d1261e", "#6167e6", "#3db322", "#a12cbb"];
    var newImgNumber =Math.floor(Math.random()*myImages.length);
    document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
    document.body.style.backgroundColor = myColors[newImgNumber];
}
window.onload=changeImg;

大した違いはなかったので、css の背景も不快感のない灰色に調整しました。

4

2 に答える 2

2

これはどう :

imgパスを単に保存するのではなく、のように保存しcolor url('url-to-image')、それを呼び出すときに背景として使用します。

したがって、配列は次のようになります:['color1 url(url-1)', 'color2 url(url-2)', ...]そして使用するJavaScriptを変更しますdocument.body.style.background = array[array-index];

/*Makes background image change when refreshed*/
function changeImg(imgNumber) {
    var myImages = ["red url(../img/background_tile.png)", "blue url(../img/background_tile_blue.png)", "green url(../img/background_tile_green.png)", "orange url(../img/background_tile_purple.png)"]; 
    var newImgNumber =Math.floor(Math.random()*myImages.length);
    document.body.style.background = myImages[newImgNumber];
}
window.onload=changeImg;
于 2012-11-08T13:40:02.507 に答える
1

次のように、スタイリングを css クラスに委譲することを常にお勧めします。

テーマ.css:

.theme-1 {
    background:red url(../img/background_tile.png);
}
.theme-2 {
    background:green url(../img/background_tile_green.png);
}
.theme-3 {
    background:orange url(../img/background_tile_purple.png);
}

適用-theme.js:

/* Apply random class to body */
function setRandomTheme() {
    var styles = ["theme-1", "theme-2", "theme-3"],
        random = Math.floor(Math.random() * styles.length);
    document.body.className += ' ' + styles[random];
}

また、背景を即座に変更したい場合は、スタイル設定されていないコンテンツをフラッシュせずに、タグsetRandomThemeを閉じる直前に呼び出します。body

<body>
    <p>La-la-la, some content</p>
    … skipped some code …
    <script type="text/javascript">setRandomTheme();</script>
</body>

またはDOMContentLoadedイベントから:

setRandomTheme 宣言の後にこれを apply-theme.js に追加するだけです:

document.addEventListener('DOMContentLoaded', function () {
    setRandomTheme(); 
});
于 2012-11-08T14:19:40.743 に答える