Javascript Array-在加载浏览器时获取随机照片以显示

时间:2018-11-06 20:51:57

标签: javascript html arrays random

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();
});

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

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

1)初始调用setRandomImage函数

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

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>

答案 1 :(得分:0)

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

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()中,让按钮的click事件调用该函数,然后将onload="rans()"添加到body标签,您将获得相同的功能,并在页面加载时获得随机图像。

关键代码更改: 更改此:

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()">

答案 2 :(得分:0)

document.addEventListener('DOMContentLoaded',theSameHandlerAsForClick);

答案 3 :(得分:-1)

更改此行

randImg.src = movieImages[randNum] ;

这个人

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