Load Random Image From Directory on Page Load Without a Listed Array of File Names

前端 未结 4 1027
一向
一向 2021-01-26 21:32

I\'ve done some looking around on the site and every time I pull up a solution to this problem, one of the requirements is to have a naming convention and a list of every image

4条回答
  •  Happy的楠姐
    2021-01-26 22:16

    First you need to get your file list from server side. then you can use a code like following:

      var imageList = //your image list as an array of urls;
      var imageNumber = Math.random() * imageList.length; //gives you a random number in the range of imageList's size
      var imageToLoad = new Image();
      imageToLoad.addEventListener("load", function(){
          console.log( "image is loading" );
          $('#my-container').append(this); //in this case this will return image dom
      });
      imageToLoad.src = imageList[imageNumber];
    

    this will add image to a container with id 'my-container' its just an example you can do anything you want using 'this'

提交回复
热议问题