简体   繁体   English

在JavaScript数组中调整幻灯片图像的大小以适合视口

[英]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. 我有一个项目正在尝试使用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. 它们解决了重新调整大小的问题,但不适用于数组中的图像,或者该解决方案要求将图像添加到HTML中,这不是我要尝试做的。 I've attempted to use CSS, but it does not work and adding lines in the javascript using 我尝试使用CSS,但无法正常工作,请使用

$("#libImage").style.width = '50%'; $(“#libImage”)。style.width = '50%';
$("#libImage").style.height = 'auto'; $(“#libImage”)。style.height ='自动';

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 的HTML

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

Javascript Java脚本

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/ https://jsfiddle.net/e6ywm5j2/5/

Instead of background: url() I used img tag 代替background: url()我使用了img标签

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

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

And css changes are: 和CSS更改是:

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

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

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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