How can I randomly load a single image from my Ima

2019-08-04 10:48发布

I'm very new to Jquery/Javascript and I'd like to load a single image onto my homepage from my image directory so that upon refreshing a new random image appears. Is there a way for Jquery to simply access my images folder and load any image at random? I am currently using a JS code that requires I type each image name that I would like loaded. This is exhaustive and while I may not know much about Jquery, I think this can be done in a cleaner fashion. my apologies in advance if i'm being naive.

1条回答
时光不老,我们不散
2楼-- · 2019-08-04 11:16

When you link to the them in your HTML markup you can use the same link in a js function to link to them like so.

Not sure how your directory structure is set up but as an example.

  • dir
    • images
      • image1.jpg
    • scripts
      • script.js
    • style
    • index.html

in your js file you can just link to images/image1.jpg

in the <header> tag add:

<script type="text/js" src="js/script.js" />

Then in your script.js file do one of these:

//Raw Javascript

  function changeMe()
  {
    document.getElementById("changeMe").src = "images/" + getRandomImage();
  }

  <img id="changeMe" onLoad="changeMe()" src="images/default.jpg" />


 //JQuery
  $(document).ready(function(){
    $("#changeMe").src("images/" + getRandomImage());
  });
  <img id="changeMe" src="images/default.jpg" />

Then all you need to do is write the function that will return a random image from that directory. There are tons of ways to do this but for simplicity.

function getRandomImage() {
  var images = ["image1.jpg","image2.jpg","image3.jpg"];

  return images[Math.floor(Math.random() * images.length)];
}

JSFiddle

查看更多
登录 后发表回答