为什么函数不会匹配不同数组的宽度和高度

Why won't function match width and height from varying arrays?

本文关键字:高度 数组 函数 为什么      更新时间:2023-09-26

我之前有以下函数,它被冗余的重复变量所破坏。所以我想改进它并将图像存储到数组中。但是,即使使用与先前脚本相同的上下文标记,它也不会从数组中检测到图像值并将其与item匹配。我不知道为什么。我将每个项目设置为检查不同图像大小的实例,然后执行if状态的操作。

工作

小提琴(非工作脚本):

工作

小提琴:(工作脚本):

我不是没有表达数组的正确值吗?我觉得我想太多了,忽略了一些小事。但老实说,我被难住了。

var top_horizontalvert_mobile = ['320 x 50', '300 x 100', '300 x 50', '250 x 250', '120 x 60', '240 x 400', '180 x 150', '125 x 125'];
var top_horizontal_desktop = ['729 x 90', '468 x 60'];                                                                   
var bottom_horizontal_desktop = ['930 x 180', '336 x 280'];                             
var bottom_vert_mobile = ['234 x 60'];
var middle_vert_mobile = ['300 x 250'];
var right_vert_desktop = ['120 x 600', '160 x 600'];
$("#carousel-container-mobile, #carousel-container-desktop").on('slid.bs.carousel', function() {
  $('.item').each(function() {
      var imgs = $('.item');
      var w = $(img).width();
      var h = $(img).height();
      var img = $('img', this);
      if (w == top_horizontalvert_mobile && h == top_horizontalvert_mobile) {
         img.addClass('top, smaller-img');
      }
      if (w == top_horizontal_desktop && h == top_horizontal_desktop) {
         img.addClass('top, larger-img');
      }
      if (w == bottom_vert_mobile && h == bottom_vert_mobile) {2
         img.addClass('bottom, smaller-img');
      }
      if (w == bottom_horizontal_desktop && h == bottom_horizontal_desktop) {
         img.addClass('bottom, larger-img');
      }
      if (w == middle_vert_mobile && h == middle_vert_mobile) {
         img.addClass('middle, smaller-img');
      }
      if (w == right_vert_desktop && h == right_vert_desktop) {
         img.addClass('right, smaller-img');
      }
      if (w == middle_vert_mobile && h == middle_vert_mobile) {
         img.addClass('right, smaller-img');
      }
   });
});

两个脚本之间的主要区别在于如何比较值。

在工作脚本中,您直接比较数字:

if (img.width() == 320 && img.height() == 50)

在非工作脚本中,您实际上是将数字与数组进行比较。

if (w == top_horizontalvert_mobile)

如果我们换成更文字的值:

if (img.width() == ['320 x 50', '300 x 100', '300 x 50', '250 x 250', '120 x 60', '240 x 400', '180 x 150', '125 x 125']

而且永远不会有数字将成为数组的情况,因为数组是不同的数据类型。

根据我所看到的,您正在尝试将每个宽度和高度与数组中的每个值进行比较,但这需要以下最少的步骤:

  1. 将数组转换为多维数字数组,因为将其保留为字符串需要您解析数据(这比必要的工作量更多。因此,您将拥有[[320,50],[300,100]...],而不是[320 x 50', '300 x 100' ...]`

  2. 使用 for 循环循环访问数组的每个值,以便进行比较。请参阅Codecademy的循环教程以了解更多信息。

如果您有任何其他问题,请告诉我!

顺便说一句,在查看您的工作脚本并寻找您要执行的操作之后,您似乎正在尝试通过jQuery根据图像大小应用不同的样式。您为什么不将类直接应用于图像本身,因为您似乎对图像大小有非常具体的要求?