簡體   English   中英

Javascript Array-在加載瀏覽器時獲取隨機照片以顯示

[英]Javascript Array - getting random photo to display when browser loads

免費代碼營項目

我正在研究一個致敬頁面項目,並決定向該項目添加一個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();
});

有什么建議么?

正如用戶在注釋中指出的那樣,您想利用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> 

將您的隨機代碼放入函數中,並在加載和按下按鈕時調用該函數,如下所示。 多運行一次代碼段,以查看生成的隨機圖像。 下面是一個工作示例。

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

document.addEventListener('DOMContentLoaded',theSameHandlerAsForClick);

改變這條線

randImg.src = movieImages[randNum] ;

通過這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM