【问题标题】:Javascript HTML display random images in nav barJavascript HTML在导航栏中显示随机图像
【发布时间】:2020-04-11 19:35:58
【问题描述】:

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

【问题讨论】:

    标签: javascript html


    【解决方案1】:

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

    根本问题在于您声明数组的方式。

    【讨论】:

      猜你喜欢
      • 2013-11-10
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多