특정 폴더에서 임의의 사진이있는 캐 러셀에 필요한 Javascript는 무엇입니까?

Nov 18 2020

작게 보이는 문제가 있지만 더 이상 밤에 잠을 자지 못합니다. 아마 너무 많이 생각하고 있고 올바른 길을 잃어 버렸습니다!

저는 Bootstrap 4를 프레임 워크로 사용하고 있습니다. 페이지를 새로 고칠 때마다 이미지를 임의의 순서로 표시하는 상호 작용이없는 자동 전체 페이지 캐 러셀을 삽입해야합니다. 이미지가 많기 때문에 특정 폴더에서 이미지를 가져와야합니다.

누구든지 내가 필요한 Javascript로 나를 도울 수 있습니까 ??

내가 시작하는 기본 코드 아래. 분명히 이렇게 작성하면 문제없이 작동하고 필요한 스타일을 반영하지만 이미지는 항상 동일하고 표시된 순서대로 표시됩니다.

미리 감사드립니다

<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Stencil+Text&family=Big+Shoulders+Text&family=Goldman&family=Heebo&family=Quicksand&family=Shadows+Into+Light&display=swap" rel="stylesheet">
    <style media="screen">
        .carousel-inner > .carousel-item {
            min-height: 800px;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }
    </style>
    <title></title>
</head>
<body>
    <section class="nopadding">
        <div id="carouselProjRec" class="carousel slide carousel-fade" data-ride="carousel" interval="1800">
          <div class="carousel-inner">
                <div class="carousel-item transparent" style="background-image: url(img/car4.jpg)">
                </div>
                <div class="carousel-item active transparent" style="background-image: url(img/car3.jpg)">
                </div>
                <div class="carousel-item transparent" style="background-image: url(img/car8.jpg)">
                </div>
                <div class="carousel-item transparent" style="background-image: url(img/car7.jpg)">
                </div>
                <div class="carousel-item transparent" style="background-image: url(img/car6.jpg)">
                </div>
                <div class="carousel-item transparent" style="background-image: url(img/car11.jpg)">
                </div>
            </div>
          </div>
    </section>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>

답변

PraveenKumarPurushothaman Nov 18 2020 at 19:47

안타깝게도 디렉토리에서 데이터를 읽는 것은 JavaScript에서 지원되지 않습니다. 디렉토리를 읽고 HTML로 추가하려면 PHP 또는 Node JS와 같은 서버 측 언어가 필요할 수 있습니다.

예를 들어 PHP 인 경우 List all files in one directory PHP 와 같은 작업을 수행 할 수 있습니다 . 해당 배열을 사용하여 배열을 만들 수 있습니다.

<?php
  foreach($files as $file) {
    echo '<div class="carousel-item transparent" style="background-image: url(img/' . $file . ')"></div>';
  }

또는 Node JS를 사용하는 경우 여전히 더 간단합니다.

const directoryPath = path.join(__dirname, 'Documents');
//passsing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    } 
    //listing all files using forEach
    files.forEach(function (file) {
        // Do whatever you want to do with the file
        console.log('<div class="carousel-item transparent" style="background-image: url(img/' + file + ')"></div>'); 
    });
});

궁극적으로이를 위해서는 서버 측 언어가 필요합니다.

DamV Nov 19 2020 at 00:36

이 JS가 작동합니다 ..

<div class="container-fluid nopadding" style="width:100vw; min-height: 400px;">

<script language="javascript">
  var delay=1500 //set delay in miliseconds
  var curindex=0

  var randomimages=new Array()

    randomimages[0]="img/car1.jpg"
    randomimages[1]="img/car5.jpg"
    randomimages[2]="img/car2.jpg"
    randomimages[3]="img/car4.jpg"
    randomimages[4]="img/car3.jpg"
    randomimages[5]="img/car6.jpg"

  var preload=new Array()

  for (n=0;n<randomimages.length;n++)
  {
    preload[n]=new Image()
    preload[n].src=randomimages[n]
  }

  document.write('<img width="100%" height="100%" class="img-size" <img name="defaultimage" src="'+randomimages[Math.floor(Math.random()*(randomimages.length))]+'">')

  function rotateimage()
  {

  if (curindex==(tempindex=Math.floor(Math.random()*(randomimages.length)))){
  curindex=curindex==0? 1 : curindex-1
  }
  else
  curindex=tempindex

    document.images.defaultimage.src=randomimages[curindex]
  }

  setInterval("rotateimage()",delay)

</script>

 <!--  Random image slideshow - Thanks to Tyler Clarke ([email protected])
  For this script and more, visit http://www.javascriptkit.com -->