2012-12-16 100 views
0

我試圖使用下拉菜單來改變身體的背景圖像(ID =「架子」):如何通過「選擇」標籤更改背景圖片

<script type="text/javascript"> 
function changeTheme() 
{document.getElementById("shelf").style.backgroundImage = "url("+theme+")"; 
    var e = document.getElementById("themes"); 
    var theme = e.options[e.selectedIndex].value; 
} 
</script> 
</head> 
<body id="shelf"> 
<select id="themes" onChange="changeTheme()"> 
    <option value="images/bg/default.png">Default</option> 
    <option value="images/bg/oriental.png">Oriental</option> 
    <option value="images/bg/office.png">Office</option> 
    <option value="images/bg/old.png">Old</option> 
</select> 
</body>  

但我不知道爲什麼它不起作用..代碼中的問題在哪裏?

+1

您應該在嘗試使用它之前設置'theme'變量**?而身體將是'document.body'! – adeneo

+0

錯誤,您在定義之前使用'theme'變量。 –

回答

0

它的工作。

function changeTheme() { 
    var e = document.getElementById("themes"); 
    var theme = e.options[e.selectedIndex].value; 
    document.getElementById("shelf").style.backgroundImage = "url(" + theme + ")"; 

} 
0

你看到的行爲究竟是什麼?

試試這個:

<html> 
<head> 
<script type="text/javascript"> 
function changeTheme() 
{ 

    var e = document.getElementById("themes"); 
    var theme = e.options[e.selectedIndex].value; 
    console.log(theme); 
    document.getElementById("shelf").style.backgroundImage = "url("+theme+")"; 
} 
</script> 
</head> 
<body id="shelf"> 
<select id="themes" onChange="changeTheme()"> 
    <option value="images/bg/default.png">Default</option> 
    <option value="images/bg/oriental.png">Oriental</option> 
    <option value="images/bg/office.png">Office</option> 
    <option value="images/bg/old.png">Old</option> 
</select> 
</body>  
</html>