如何在JS里添加DIV背景

两个head之间的代码如下

<head>
<meta charset="utf-8">
<title>测试</title>
<link rel="shortcut icon" href="../picture/favicon.ico">
<script type="text/javascript">

bg=new Array(2);
bg[0]='../picture/background-1-1.png'
bg[1]='../picture/background-2-1.png'
bg[2]='../picture/background-3-1.png'
index=Math.floor(Math.random()*bg.length);
document.write("<body background="+bg[index]+">")

</script>

<link href="../style/1.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../style/js.js"></script>

</head>

我弄了个随机背景的效果 背景图片显示和随机效果没有任何问题 我想在界面唯一一个div让它对应body的背景对应的发生变化

当body background是background-1-1.png时div显示background-1-2.png
当body background是background-2-1.png时div显示background-2-2.png
当body background是background-3-1.png时div显示background-3-2.png
以此类推
我在</script>的上方加了document.write("<div background="+bg[index]+">")但div图片不显示

请问如何做

思路:

    获取元素

    修改元素的CSS样式

代码:

<div id="div"></div>
<script>
    var oDiv = document.getElementById('div');
    with(oDiv){
        background:'#ccc',
        width:'100px',
        height:'100px'
    }
</script>
温馨提示:答案为网友推荐,仅供参考
相似回答