【问题标题】:Javascript Array - getting random photo to display when browser loadsJavascript Array - 在浏览器加载时获取随机照片显示
【发布时间】:2018-11-06 20:51:57
【问题描述】:

Free Code Camp Project

我正在开发一个致敬页面项目,并决定向该项目添加一个 javascript 随机照片数组。这工作正常,但我不知道如何在浏览器重新加载时显示随机照片。

这是我的html

<div id="albumCovers"></div>
<button id='randomBut'>View Random Album Covers</button>
<div><img id='movieImg'></div>

这里是javascript

var randomizer = document.getElementById("randomBut");
var randImg = document.getElementById("movieImg");

var movieImages = [
    "all.jpg", 
    "dontgrowup.jpg",
    "everythingSux.jpg",
    "enjoy.jpg",
    "college.jpg",
    "hyper.jpg",
    "cooltobeyou.jpg"
];

randomizer.addEventListener("click", function()
{
    var randNum = Math.floor(Math.random() * movieImages.length) + 0;
    randImg.src = movieImages[randNum];
    randomizer.click();
});

有什么建议吗?

【问题讨论】:

标签: javascript html arrays random


【解决方案1】:

正如 cmets 中的一位用户所指出的,您想利用 DOMContentLoaded 事件。您可以在下面的代码中看到我创建了一个init 函数,该函数在DOMContentLoaded 被触发时被调用。 init 函数的工作是:

1) 对setRandomImage 函数进行初始调用

2) 将setRandomImage 设置为randomizer 上的click 事件处理程序

var randomizer = document.getElementById("randomBut");
var randImg = document.getElementById("movieImg");
var movieImages = [
  "all.jpg",
  "dontgrowup.jpg",
  "everythingSux.jpg",
  "enjoy.jpg",
  "college.jpg",
  "hyper.jpg",
  "cooltobeyou.jpg"
];


//When the HTML document has been completely loaded and parsed
document.addEventListener("DOMContentLoaded", init);

function init() {
  //Make an inital function call ("when the browser loads")
  setRandomImage();

  //Attach a click event listener to the random button
  randomizer.addEventListener("click", setRandomImage);
}


//Put this code in a function since we want to call it multiple times
function setRandomImage() {
  var randNum = Math.floor(Math.random() * movieImages.length) + 0;
  randImg.src = movieImages[randNum];

  //randomizer.click(); -- I dont understand the point of this line of code, so I commented.

  console.log(`Displaying ${randImg.src}`)
}
<div id="albumCovers"></div>
<button id='randomBut'>View Random Album Covers</button>
<div><img id='movieImg'></div>

【讨论】:

    【解决方案2】:

    document.addEventListener('DOMContentLoaded', theSameHandlerAsForClick);

    【讨论】:

      【解决方案3】:

      将您的随机代码放入一个函数中,并在加载和按下按钮时调用该函数,如下所示。多次运行 sn-p 以查看生成的随机图像。下面是一个工作示例。

      var randomizer = document.getElementById("randomBut");
        var randImg = document.getElementById("movieImg");
        var movieImages = ["https://image.ibb.co/caPP3V/all.jpg", 
        "https://image.ibb.co/btn2OV/dontgrowup.jpg",
         "https://image.ibb.co/kQoHOV/everything-Sux.jpg",
         "https://image.ibb.co/c2UP3V/enjoy.jpg",
         "https://image.ibb.co/ifbFAA/college.jpg",
         "https://image.ibb.co/fe7Yxq/hyper.jpg",
         "https://image.ibb.co/dKtj3V/cooltobeyou.jpg"];
      
       
       randomizer.addEventListener("click", function(){
          rans();
        });
      
      function rans(){
        var randNum = Math.floor(Math.random() * movieImages.length) + 0  
          
          randImg.src = movieImages[randNum] ;
      }
      #main {
      	margin: 0;
      }
      
      #headline {
      	background: black;
      	margin: auto;
      	width: 100%;
      }
      
      /* The code below makes the main image able to shrink properly for phones, and place the image in its own line. "height: auto;" keeps the original aspect ratio of image */
      #logo {
      	max-width: 100%;
      	display: block;
      	margin: auto;
      	height: auto;
      	padding-top: 10px;
      	padding-bottom: 30px;
      }
      
      h1 {
      	color: white;
      	text-align: center;
      	font-family: roboto;
      	padding-bottom: 10px;
      }
      
      #history{
      	color: black;
      	text-align: center;
      	font-family: roboto;
      	padding-bottom: 10px;
      }
      
      #content {
      	background: white;
      	margin: auto;
      }
      
      #milo {
      	max-width: 100%;
      	display: block;
      	margin: auto;
      	height: 200px;
      	padding-top: 10px;
      	padding-bottom: 30px;
      
      }
      
      #img-div {
      	background: black;
      	margin: auto;
      }
      
      #img {
      	max-width: 100%;
      	display: block;
      	margin: auto;
      	height: auto;
      	padding-top: 40px;
      	padding-bottom: 30px;
      }
      
      #img-caption {
      	color: white;
      	text-align: center;
      	font-family: roboto;
      	padding-bottom: 30px;
      }
      
      #albumCovers {
      	padding-top: 35px;
      }
      
      #randomBut {
      	display: block;
      	margin: auto;
      	font-size: 25px;
      }
      
      #movieImg {
      	display: block;
      	margin: auto;
      	height: 300px;
      	width: 300px;
      	padding-top: 40px;
      	padding-bottom: 30px;
      }
      
      #wiki {
      	text-align: center;
        padding-top: 35px;
      	padding-bottom: 35px;
      }
      
      a {
      	text-decoration: none;
      	font-family: roboto;
      	font-weight: 18px;
      }
      <head>
      	<title>The Descendents Tribute Page</title>
      	<link rel="stylesheet" type="text/css" href="style.css">
      	<link href="https://fonts.googleapis.com/css?family=Poppins|Roboto:400,500,700" rel="stylesheet">
      </head>
      <body id="main" onload="rans()">
      
      <div id="main">
      
      <div id="headline">
      
      	<img id="logo" src="https://image.ibb.co/fDZPnq/descendents.jpg" alt="descendents" border="0">
      
      	<h1 id="title">A tribute to one of the most influential bands in Punk Rock</h1>
      </div>
      
      	<div class="content">
      		<img id="milo" src="https://image.ibb.co/dmcNqA/milo.jpg">
      
      		<h1 id="history">HISTORY</h1>
      		<ul id="tribute-info">
      			<li>1977 - The Descendents was started by original guitarist Frank Naventta</li>
      			<li>1978 - Bill Stevenson would join the band as drummer and became one of the main songwriters. Tony Lombardo joined as bassist.</li>
      			<li>The band's music at the time was described by Stevenson as a "coffee'd-out blend of rock-surf-pop-punk music".</li>
      			<li>1979 - The band enlisted Milo Aukerman as their vocalist, who would go on to become the iconic face of the band.</li>
      			<li>1981 - Fat ep was released</li>
      			<li>1982 - "Milo Goes To College" was released, and is considered one of the most influential albums in punk rock.</li>
      			<li>The band went on hiatus from 1983-1985 while Milo was in college. Bill Stevenson had joined Black Flag in this time. Frank Navetta Burned all his equipment and never returned to the band.</li>
      			<li>1985 - The band reformed and released the album "I Don't Want to Grow Up"</li>
      			<li>1986 - "Enjoy" was released. Karl Alvarez joined as bassist, and Stephen Egerton joined as guitarist.</li>
      			<li>1987 - "All" was released. Milo left the band after touring for the album had finished. The remaining members carried on under the name "All"   </li>
      			<li>1996 - The band had reformed with Aukerman, and released the album "Everything Sux" on Epitaph Records</li>
      			<li>1997 - Aukerman left again to pursue his chemistry career</li>
      			<li>2002-2004 - The band began working on a new album in the early 2000s, with Aukerman doing vocal work from a different studio in Delaware.</li>
      			<li>2004 - "Cool to be you" was released on Fat Wreck Chords.</li>
      			<li>2008 - Original guitarist Frank Navetta passed away.</li>
      			<li>2010 - The band reunited again to play occasional one-off shows, but it was never considered a full reunion.</li>
      			<li>2013 - "Filmage" was released, which was a documentary about Descendents and All.</li>
      			<li>2016-present - "Hypercaffium Spazzinate" was released. Aukerman had left his career as a chemist, and the band has since returned to touring full time.</li>
      		</ul>
      
      		<div id="img-div">
      		<img id="img" src="https://image.ibb.co/iy08DV/band-Photo.png" alt="band-Photo" border="0">
      		<div id="img-caption">From left to right: Karl Alvarez (bass), Bill Stevenson (drums), Stephen Egerton (guitar), Milo Aukerman (vocals)
      		</div>
      	</div>
      
      	<div id="albumCovers"></div>
      	<button id='randomBut'>View Random Album Covers</button>
      	<div><img id='movieImg'></div>
      	</div>
      
      
      	<div id="wiki">
      		<a href="https://en.wikipedia.org/wiki/Descendents" target="_blank">Descendents Wikipedia</a>
      	</div>
      </div>
      <script type="text/javascript" src="tribute.js"></script>
      </body>
      </html>

      通过添加将用于按钮的onclick 绑定中使用的代码移动到其自己的函数rans() 中,让按钮的单击事件调用该函数,然后将onload="rans()" 添加到正文标记中,您将得到相同的结果功能并在页面加载时获得随机图像。

      关键代码更改: 改变这个:

      randomizer.addEventListener("click", function()
      {
          var randNum = Math.floor(Math.random() * movieImages.length) + 0;
          randImg.src = movieImages[randNum];
          randomizer.click();
      });
      

      到这里:

      randomizer.addEventListener("click", function(){
          rans();
        });
      
      function rans(){
        var randNum = Math.floor(Math.random() * movieImages.length) + 0  
      
          randImg.src = movieImages[randNum] ;
      }
      

      并将onload添加到body标签:

      <body id="main" onload="rans()">
      

      【讨论】:

        【解决方案4】:

        改变这一行

        randImg.src = movieImages[randNum] ;
        

        这个

        randImg.setAttribute('src', movieImages[randNum]) ;
        

        【讨论】:

        • 我只是尝试过,但它没有做任何事情 randomizer.addEventListener("click", function() { var randNum = Math.floor(Math.random() * movieImages.length) + 0 randImg. setAttribute('src', movieImages[randNum]) ; randomizer.click();
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-01
        • 2013-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多