【问题标题】:jQuery: add classes according to image proportionsjQuery:根据图像比例添加类
【发布时间】:2012-09-04 16:49:25
【问题描述】:

你好,

我正在尝试根据每个图像的比例(横向/纵向/正方形)为每个图像添加类。此代码在 JSfiddle 中有效,但在网站上无效(本地或服务器上):

$(document).ready(function()
{
    $('img').addClass('wide');
    $.each($('img'), function()
    {
        var image = $(this);

        if (image.height() > image.width()) {
            image.removeClass('wide');
            image.addClass('tall');
        } else if (image.height == image.width()) {
            image.removeClass('wide');
            image.addClass('square');
        }
    });
});​

这是我的 JSfiddle:http://jsfiddle.net/LYxv6/

【问题讨论】:

  • 您的网站 HTML 是什么样的(发布摘录)。

标签: jquery


【解决方案1】:

您的代码在 jsfiddle 上运行的原因是该站点(默认情况下)将您的代码包装在 onload 处理程序中。一旦所有图像加载完毕,就会调用此处理程序,这与 $(document).ready() 不同,后者只等待 DOM 结构完成。

如果您利用采用函数参数而不是字符串的addClass 版本,则更改类的函数是微不足道的:

$(window).on('load', function() {
    $('img').addClass(function() {
        if (this.height === this.width) {
            return 'square';
        } else if (this.height > this.width) {
            return 'tall';
        } else {
            return 'wide';
        }
    });
});

在回调中this<img>元素本身,你可以直接访问它的.width.height属性而无需使用jQuery。

这应该比在 .each() 循环中重复调用 jQuery 函数更有效。

【讨论】:

  • 很好的回答伙伴,来自我的 +1。
  • 有效。我可以使用此代码同时向 img parrent div 添加一个类吗?我尝试注入 (this).parent().addClass("squarediv");但这不起作用。
  • $(this.parentNode).addClass('squarediv') 应该工作,但你需要把它放在相关的 return 声明之前。
【解决方案2】:

你应该运行这个脚本

$(window).load()

...否则(准备就绪)可能会发生图像尚未加载且访问时大小仍然未知的情况。

您还在这里忘记了一些括号:

else if (image.height == image.width()) {

应该是

else if (image.height() == image.width()) {

【讨论】:

  • 实际上在图像标签上他最好只使用this.width
  • 我还需要 var image = $(this);使用 this.width 时
  • 是的,因为 addClass 和 removeClass 仍然需要 image
  • @Dr.Molle 除非您根据我的回答使用.addClass(function() { ...})
  • 请看一下原始问题,这就是我的答案的目的。这里的cmet更多的是关于“优化”,与问题无关。
【解决方案3】:

更改为 $('img').each 并且在 image.height() 处缺少括号(这是一个函数)

$(window).load(function() {

$('img').addClass('wide');

$('img').each(function() {
    var image = $(this);

    if (image.height() > image.width()) {
        image.removeClass('wide');
        image.addClass('tall');
    }
    else if (image.height() == image.width()) {
        image.removeClass('wide');
        image.addClass('square');
    }

});

});

【讨论】:

    【解决方案4】:

    尝试在if else if 语句中使用变量:

    Here is jsFiddle.

        var biggerVal = image.height() > image.width();
        var equalVal = image.height() == image.width();
    
        if ( biggerVal ) {
            image.removeClass('wide');
            image.addClass('tall');
        } else if ( equalVal ) {
            image.removeClass('wide');
            image.addClass('square');
        }
    

    关于这个问题的同样问题:How to build simple sticky navigation with jQuery?

    【讨论】:

    • 在这种情况下没有太多点声明一个只被使用一次的变量......事实上,你应该缓存.height().width(),因为那些都在进行函数调用。
    • @Alnitak 当我在问题上看到“此代码在 JSfiddle 中有效但在网站上(本地或服务器上)无效:”时,我怀疑没有声明变量,因为在长 jQuery 代码中,这发生在我之前。在 jsFiddle 上工作,但在现场却无法工作。
    • 代码倾向于在 jsfiddle 上运行但在其他地方不行的主要原因是因为 jsfiddle defaults 会在您的代码周围放置一个“onload”包装器,就像 OP 的小提琴一样.将东西移入变量将与它完全无关
    • @Alnitak 是的,你在这个例子中是对的,但是在 if else 声明中使用变量总是更好的,以防不创建 jQuery 冲突。
    • 我不知道你在说什么。
    【解决方案5】:

    在本地系统的服务器上,创建一个 .html 文件。

    将其更改为文档加载,为其中一个宽度部分添加缺失的大括号 - 并确保 .html 文件如下所示:

        <!DOCTYPE html>
        <html>
        <head>
        <meta charset=utf-8 />
        <title></title>
        <script>
           $(document).load(function() {
    
        $('img').addClass('wide');
    
        $.each($('img'), function() {
            var image = $(this);
    
            if (image.height() > image.width()) {
                image.removeClass('wide');
                image.addClass('tall');
            }
            else if (image.height() == image.width()) {
                image.removeClass('wide');
                image.addClass('square');
            }
    
        });
    
    });​
        </script>
        <style>
        img{
    height:250px;
    }
    .wide{
    border:10px solid #aed;
    
    }
    .tall{
    border:10px dashed #dea;
    
    }
    .square{
    border:10px dotted #ade;
    
    }​
        </style>
        </head>
        <body>
        <img src="http://24.media.tumblr.com/tumblr_m9t0dwyu0P1qjfsubo1_500.jpg"/>
        <img src="http://24.media.tumblr.com/tumblr_m9iqv8oQl01qcpwsso1_500.jpg "/>
        <img src="http://25.media.tumblr.com/tumblr_m9n4kyf8aA1r1thfzo5_1280.jpg"/>  
        </body>
        </html>
    ​
    

    您可以将&lt;style&gt;&lt;/style&gt;&lt;script&gt;&lt;/script&gt; 替换为&lt;link rel="stylesheet" type="text/css" href="yourstyle.css"/&gt;&lt;script type ="text/javascript" src="jquerywhatever.js"&gt;&lt;/script&gt;&lt;script type ="text/javascript" src="YOURSCRIPT.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案6】:

      我会这样做:

      (function ($) {
          $.fn.proportions = function (options) {
              options = $.extend(options, {
                  wideClass : 'wide',
                  tallClass : 'tall',
                  squareClass : 'square'
              });
              addProportions = function () {
                  img = $(this);
                  var ratio = img.width() / img.height();
                  if (ratio > 1) {
                      return img.addClass(options.wideClass);
                  }
                  if (ratio === 1) {
                      return img.addClass(options.squareClass);
                  }
                  return img.addClass(options.tallClass);
              };
              return this.each(function () {
                  if ($(this).width() !== undefined) {
                      addProportions.call(this);
                  } else {
                      $(this).on('load', addProportions);
                  }
              });
          };
      }(jQuery));
      
      jQuery(function ($) {
          jQuery('img').proportions();
      });​
      

      将其放入插件中使其可重用。我没有像 jsfiddle 那样使用 window.load,而是将该函数附加到每个图像的加载事件中,以便立即添加该类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-06
        • 2018-11-26
        • 1970-01-01
        • 2017-04-06
        • 2017-11-30
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        相关资源
        最近更新 更多