简体   繁体   中英

Manual JavaScript Slideshow with Dynamic images

I am trying to create a make shift slideshow within the browser.

A user would be able to use

<input type='file' id="upload" multipule>

to upoad their images once this is complete it would show the first image (which would be named filename1.jpg) and the by pressing the right arrow key it would switch to filename2.jpg etc... etc...

I can work out how to get a slideshow to work, but I cannot seem to get one to work dynamicly.

Here's what I have:

JavaScript

function readURL(input) {
    var url = input.value;
    var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
    if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
        var reader = new FileReader();
        reader.onload = function (e) {
        $('#img').attr('src', e.target.result);
        $("#upload").hide();
      }
        reader.readAsDataURL(input.files[0]);
    }
}

CSS

#slides {
  position: fixed;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  z-index: -1;
}
#slides img {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  min-width: 50%;
  min-height: 50%;
}

HTML

<div id="upload" class="container">
    <form action="">
     Upload Slides:<input type='file' id="upload" multiple onchange="readURL(this)" />
    </form>
</div>
<div id="slides">
  <img id="img" src="#" alt="your image" />
</div>

Managed to solve this using:

var img = new Array();
var uploadIndex = 0;
var imageIndex = 0;

function readURL(input) {
 if (input.files && input.files[0]) {
    var fileList = input.files;
    for (var i = 0, file; file = fileList[i]; i++) {
        var reader = new FileReader();

        reader.onload = function (e) {
            img[uploadIndex] = new Image();
            img[uploadIndex].src = e.target.result;

            if (uploadIndex === 0) {
                $('#img').attr('src', img[0].src);
                $("#uploadForm").hide();
            }

            uploadIndex++;
        };
        reader.readAsDataURL(input.files[i]);
    }

 }
}

document.onkeydown = checkKey;

function checkKey(e) {

 e = e || window.event;

if (e.keyCode == '37') {
    if (imageIndex === 0) {
        //do nothing
    } else {
        imageIndex--;
        $('#img').attr('src', img[imageIndex].src);
    }
}
if (e.keyCode == '39') {

    if (imageIndex >= uploadIndex) {
        //do nothing
    } else {
        imageIndex++;
        $('#img').attr('src', img[imageIndex].src);
    }
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM