简体   繁体   中英

How can I passing partial array to left and right Gallery buttons?

This code works and creates a modal with a single image in it depending upon which thumbnail is clicked.

I trim away "./thumbnails/tn" and replace it with./mypix/ to show the high res image in the modal. (Thumbnails are in a different directory with a name prefix of tn).

The 500 images have ID myImg1.... to myImg500. But I don't want to include myImg51, myImg52, myImg53, and a few others.

How do I pass the array of images to Java and add left and right buttons to my code? I would like the user to be able to browse through the images. I don't want thumbnails on the image page as I want to maximize the view of the photograph.

And I would like it to wrap so the last image right button shows the first image.

<style>
body {font-family: Arial, Helvetica, sans-serif;}

.myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.5s;
}

.myImg:hover {opacity: 0.7;}

.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 0px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

.modal-content {
  margin: auto;
  display: block;
  width: 100%;
  max-width: 1500px;
}

.modal-content {  
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {-webkit-transform:scale(0)} 
  to {-webkit-transform:scale(1)}
}

@keyframes zoom {
  from {transform:scale(0)} 
  to {transform:scale(1)}
}

.close {
  position: absolute;
  top: 20px;
  right: 300px;
  color: #f1f1f1;
  font-size: 50px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

@media only screen and (max-width: 700px){
  .modal-content {
    width: 100%;
    max-width: 700px;
  }
}
</style>
</head>
<body>
<img class="myImg" id="myImg1" src="./thumbnails/tnPIC012386.jpg" style="width:100%;max-width:300px" onclick="myFunctionElt(this);"><br>
<img class="myImg" id="myImg2" src="./thumbnails/tnPIC012436.jpg" style="width:100%;max-width:300px" onclick="myFunctionElt(this);"><br>
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
</div>

<script>
function myFunctionElt (elt) {
        var span = document.getElementsByClassName("close")[0];
            span.onclick = function() { 
            modal.style.display = "none";
        }
    var strID = document.getElementById(elt.id);
    var modal = document.getElementById("myModal");
    var modalImg = document.getElementById("img01");
    modal.style.display = "block";
    var str = strID.src;
    var str1 = "./mypix/";
    var str2 = str.substr(str.length - 13);
    var res = str1.concat(str2);
    modalImg.src = res;
}
</script>

First, lets talk about getting your full set of image attributes into a data structure. I'm going to recommend using an object instead of any array. Mainly because we'll have some more flexibility in how to access it.

var images = {};

function populateImages(){
    // do stuff here to retrieve all your data about your set of images...
    // here's how to load each image into the images object... 
    var image = {
        CLASS: "myImg",
        ID: "myImg1",
        SRC: "./thumbnails/tnPIC012386.jpg",
        STYLE: "width:100%;max-width:300px",
        ONCLICK: "myFunctionElt(this);"
    };
    images[image.ID] = image;
}

populateImages();

Obviously the code above currently only puts a single image into the images object... its for demo purposes only... you'll need to make your calls to get the info about each image and/or hardcode all the image insertion there. The important part is that the set of property keys inside of the images object will be the image ids.

Assuming you get the images all loaded into the images object then you can have an array of image ids for which you don't want to display thumbnails and you can use the array.filter function to output a set of all image IDs that aren't in your excluded array

var excludedIDArray = [];
function populateExcludedIDs(){
    // do stuff to populate the array with the
    // set of id's for which you don't want thumbnails displayed
    excludedIDArray.push('myImg51');
    excludedIDArray.push('myImg52');
    excludedIDArray.push('myImgWhatever');
}

populateExcludedIDs();
var imageIDArray = Object.keys(images);
var thumbnailArray = imageIDArray.filter(id => !excludedIDArray.includes(id));

thumbnailArray is now the list of all image IDs that aren't excluded

right now you have your thumbnails hanging out as child elements of body directly... let's move them into a div so we can use script to populate all those elements more cleanly

<body>
    <div id="thumbsList">
        <img class="myImg" id="myImg1" src="./thumbnails/tnPIC012386.jpg" style="width:100%;max-width:300px" onclick="myFunctionElt(this);"><br>
        <img class="myImg" id="myImg2" src="./thumbnails/tnPIC012436.jpg" style="width:100%;max-width:300px" onclick="myFunctionElt(this);"><br>
    </div>

Now we do a function to fill up that div with whatever is in your thumbnailArray

function populateThumbnails(){
    var container = document.getElementByID("thumbsList");
    container.innerHTML = '';
    for(var index = 0; index < thumbnailArray.length; index++){
        var image = images[thumbnailArray[index]];
        var imageElement = document.createElement("IMG");
        for (var key in Object.keys(image)) {
            imageElement.setAttribute(key, image[key]);
        }
        container.appendChild(imageElement);
    }
}

populateThumbnails();

Because of the way we stored each image in the images object... basically each property of the images object is itself an object whose properties are the individual attributes of the resultant image tags that will be used in the HTML... we use the elements of the thumbnailsArray to find the image object within images... and then we create new img tag and loop through all the properties of the image object using each key:value pair to set the new img tag's attributes. Then we just add the new img tag as a child of the thumbsList div.

Now, all of your thumbs should be showing up and you can open your modal with any of them...

Before we tackle the left and right buttons,lets change up the way we call myFunctionElt... rather than passing in the full (this) from the img tags, let's just pass in (this.id):

<img class="myImg" id="myImg1" src="./thumbnails/tnPIC012386.jpg" style="width:100%;max-width:300px" onclick="myFunctionElt(this.id);">

Now, let's adjust MyFunctionElt to handle the fact that its only getting the ID and then add the setting of the current image index

// create a variable to hold the index within thumbnailArray
// of the selected image
var modalImageIndex = 0;

function myFunctionElt (eltID) {
    // set modalImageIndex
    modalImageIndex = thumbnailArray.indexOf(eltID);

    var span = document.getElementsByClassName("close")[0];
    span.onclick = function() { 
        modal.style.display = "none";
    }
    var strID = document.getElementById(eltID);
    var modal = document.getElementById("myModal");
    var modalImg = document.getElementById("img01");
    modal.style.display = "block";
    var str = strID.src;
    var str1 = "./mypix/";
    var str2 = str.substr(str.length - 13);
    var res = str1.concat(str2);
    modalImg.src = res;
}

Now we should be all set to go for the last little bit... lets add buttons to your modal template for left and right. You'll obviously want to style them however you want, what I have here will be plain and not aligned very visually pleasing.

<div id="myModal" class="modal">
  <button id="shiftLeft" onclick="shiftImage('PREVIOUS')">Previous</button>
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <button id="shiftRight" onclick="shiftImage('NEXT')">Next</button>
</div>

So, we have 2 buttons, Previous and Next... they both call a function called shiftImage() and pass in a text string... so lets define that function

function shiftImage(direction){
    switch(direction){
        case 'PREVIOUS':
            if(modalImageIndex == 0){
              modalImageIndex = thumbnailArray.length;
            }
            modalImageIndex--;
            break;
        case 'NEXT':
            modalImageIndex++;
            modalImageIndex = modalImageIndex % thumbnailArray.length;
            break;
        default:
            break;
    }
    myFunctionElt(thumbnailArray[modalImageIndex]);
}

So in the shiftImage function, we either increment or decrement modalImageIndex value. If the result is less than 0 then we set it to be the end of the thumbnailArray.. To handle the end case, we use the modulus operator to cycle it back to the beginning. Once we update the modalImageIndex value, then we call your myFunctionElt function and pass in the imageID of the newly indexed value in thumbnailArray.

At this point you should have all the moving pieces... it'll just be up to you to arrange them in your code appropriately, make adjustments to styling, and actually add the code to populate the images object and excludedIDArray

Typically questions of this nature are too broad for asking on stackOverflow... but I was bored this morning lol... cheers!

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