简体   繁体   中英

Resizing Slideshow Images In A JavaScript Array To Fit Viewport

My first post, so apologies if the formatting is bad.

I have a project where I'm attempting to create a slideshow using Javascript. I've placed the images into an array and got the slideshow running.

The problem I'm facing is that the images are much larger than the viewport. I've looked at this post as well as this post and many others. They address the issue of re-sizing, but not for images in arrays or the solution requires adding an image to the HTML, which is not what I'm trying to do. I've attempted to use CSS, but it does not work and adding lines in the javascript using

$("#libImage").style.width = '50%';
$("#libImage").style.height = 'auto';

only changes the size of what you can see of the image, not the image itself. Is this even possible for what I'm trying to do and if so, what and where should I use it get the results that I want?

Thank you very much for the help.

HTML

<div id="libImage"></div>

Javascript

var images = ["../images/lib-orange.jpg", "../images/lib-main.jpg", "../images/lib-powel.jpg", "../images/lib-ostrander.jpg"];

    $(function () {
        var i = 0;
        $("#libImage").css("background", "url(images/" + images[i] + ")");
         setInterval(function () {
            i++;
            if (i == images.length) {
                i = 0;
            }
            $("#libImage").fadeOut("slow", function () {
                $(this).css("background", "url(images/" + images[i] + ")");
                $(this).fadeIn("slow");
            });
        }, 3000);
    });

Thanks for the response, sorry for the delay. Its not the same effect that I got, but its the same problem. The pictures are not showing up scaled to the size of the viewport.

https://jsfiddle.net/e6ywm5j2/5/

Instead of background: url() I used img tag

<div id="libImage"><img src="" ></div>

and replace $("#libImage").css("background", "url(images/" + images[i] + ")"); with $("#libImage img").prop("src", images[i]);

And css changes are:

div { width: 100%; height: 100vh; text-align: center; }

img {
  max-height: 90%;
  max-width: 90%;
}

Demo

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