對于移動視圖,我為導(dǎo)航欄菜單圖標(biāo)切換按鈕制作了不同的圖像。我已將圖像放入數(shù)組中,并用于Math.Random隨機(jī)選擇圖像,但我不確定如何在 HTML 中鏈接它,以便每次加載頁面時,它都會為導(dǎo)航欄圖標(biāo)選擇一個隨機(jī)圖像。目前我已將其設(shè)置為 HTML 中的一張圖像。也不能 100% 確定我是否正確編寫了數(shù)組/隨機(jī)圖像的 JS 代碼?<div class="topnav" id="myTopnav"> <a href="home.html" >NAME</a> <ul> <li style="list-style-type: none;" class="nav-link"><a id="work" href="work.html">WORK</a></li> <li style="list-style-type: none;" class="nav-link"><a href="contact.html">CONTACT</a></li> </ul> <a href="javascript:void(0);" class="icon" onclick="myFunction()"> <img id="menuicon" src="img/menuiconcherry.png"></i> </a></div>我的導(dǎo)航欄切換的 JS:function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; }}JS隨機(jī)圖像:window.onload = randommenuicon;let menuicon = new Array ["img/menuiconwatermelon.png", "img/menuiconorange.png", "img/menuiconpineapple.png", "img/menuiconbanana.png", "img/menuiconfig.png", "img/menuiconstrawberry.png", "img/menuiconcherry.png"];function randommenuicon() {let randomnumber = Math.floor(Math.random() * menuicon.length);// let randommenuicon = menuicon[randomnumber];document.getElementById("menuicon").src = menuicon[randomnumber]; }
1 回答

波斯汪
TA貢獻(xiàn)1811條經(jīng)驗 獲得超4個贊
將您的 JS 更改為以下內(nèi)容:
let menuicon = ["img/menuiconwatermelon.png", "img/menuiconorange.png", "img/menuiconpineapple.png", "img/menuiconbanana.png", "img/menuiconfig.png", "img/menuiconstrawberry.png", "img/menuiconcherry.png"];
window.onload = function() {
let randomnumber = Math.floor(Math.random() * menuicon.length);
document.getElementById("menuicon").src = menuicon[randomnumber];
};
根本問題是由于您聲明數(shù)組的方式造成的。
- 1 回答
- 0 關(guān)注
- 147 瀏覽
添加回答
舉報
0/150
提交
取消