繁体   English   中英

使用不同大小的图像调整大小的滑块

[英]Resize slider with different sized images

我有一个带有3种图像类型的移动式第一滑块:高,水平长和正方形。 我希望水平的长图像确定滑块的大小,然后缩放并居中放置其他大小以适合其大小。 使用width:100%; height:auto; width:100%; height:auto; 在我的CSS代码中,因此图像将以相同的宽度(100%)和不同的高度加载。 然后使用JS,我想获取具有最大宽度/高度比的图像的高度,并将其用作所有图像的高度。 最后使用width:auto; height:100%; width:auto; height:100%; 用于图像,因此所有图像都适合高度。 这是我用来实现此目的的代码:

每张幻灯片具有以下HTML:

<div class="img">
      <img src="" alt="">
 </div>

CSS代码:

 .img{
     position: relative;
     vertical-align: middle;
}

 .img img{
     width:100%;
     height:auto; 
     position: absolute;
     top: 0;  
     bottom: 0;  
     left: 0;  
     right: 0;  
     margin: auto;
}

JS代码:

        $(".img img").width = "100%";
        $(".img img").height = "auto";;
        var img_h , Imgs_heights=[] , ratio=[];
        slider.item.find(".img img").each(function(){
            Imgs_heights.push($(this).height());
            ratio.push($(this).width()/(($(this).height())));
        });
        img_h = Math.max.apply(Math,ratio);
        var i = r.indexOf(img_h );
        $(".img").height(Imgs_heights[i]);
        $(".img img").css("height", "100%");
        $(".img img").css("width", "auto");

一切正常,但调整窗口大小时出现问题。 在调整大小时,图像的高度不会改变,并保持之前计算的高度。 我需要刷新页面才能看到所需的结果。 如何获得高度变化? 我在JS中添加了第一行,以强制width:100%; height:auto; width:100%; height:auto; 再次在调整大小的窗口中,但是它不起作用。

我将不胜感激。

如果我对您的理解正确,是否可以仅使用Javascript window.resize事件重新计算图像大小?

从Mozilla https://developer.mozilla.org/en-US/docs/Web/Events/resize

调整文档视图(窗口)的大小时,将触发resize事件。

您的代码可能类似于:

function resizeImages(){
   $(".img img").width = "100%";
   $(".img img").height = "auto";
   var img_h , Imgs_heights=[] , ratio=[];
   slider.item.find(".img img").each(function(){
       Imgs_heights.push($(this).height());
       ratio.push($(this).width()/(($(this).height())));
   });
   img_h = Math.max.apply(Math,ratio);
   var i = r.indexOf(img_h );
   $(".img").height(Imgs_heights[i]);
   $(".img img").css("height", "100%");
   $(".img img").css("width", "auto");
}

window.onload = function(){
  resizeImages();
};

window.onresize  = function(){
  resizeImages();
}; 

暂无
暂无

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

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