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;

现在我正在尝试将 CSSbackground-color更改为图像的颜色,以便在刷新页面时它不会在加载之前闪烁白色。

网站 - 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)', ...]并更改要使用的javascriptdocument.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);
}

应用主题.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 回答