Javascript HTML在导航栏中显示随机图像

时间:2020-04-11 11:27:42

标签: javascript html

对于移动视图,我为导航栏菜单图标切换按钮制作了不同的图像。我将图像放置在数组中,并使用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 个答案:

答案 0 :(得分:0)

将您的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];
};

潜在的问题是由于您声明数组的方式造成的。