對于移動視圖,我為導航欄菜單圖標切換按鈕制作了不同的圖像。我已將圖像放入數組中,并用于Math.Random隨機選擇圖像,但我不確定如何在 HTML 中鏈接它,以便每次加載頁面時,它都會為導航欄圖標選擇一個隨機圖像。目前我已將其設置為 HTML 中的一張圖像。也不能 100% 確定我是否正確編寫了數組/隨機圖像的 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>我的導航欄切換的 JS:function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; }}JS隨機圖像: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貢獻1811條經驗 獲得超4個贊
將您的 JS 更改為以下內容:
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];
};
根本問題是由于您聲明數組的方式造成的。
- 1 回答
- 0 關注
- 159 瀏覽
添加回答
舉報
0/150
提交
取消