jquery 只检查页面上一张图片的比率

标签 jquery css background-image

我在页面上有几个 div,我正在尝试使用 jQuery 向它们添加类。 但是 jQuery 只检查第一个背景图像的比率并将相同的类添加到所有 div。

如何检查所有背景图像的比率?

片段:

$(document).ready(function () {
    var image_url = $('.class1').css('background-image'),
        image;

    // Remove url() or in case of Chrome url("")
    image_url = image_url.match(/^url\("?(.+?)"?\)$/);

    if (image_url[1]) {
        image_url = image_url[1];
        image = new Image();

        // just in case it is not already loaded
        $.each(image).load(function () {
            //   alert(image.width + 'x' + image.height);
            var ratio = image.width / image.height;

            if (ratio > 1) {
                $(".class1").addClass("added_1");
            } else if (ratio < 1) {
                $(".class1").addClass("added_2");
            }
        });

        image.src = image_url;

    };
})

最佳答案

使用 jquery 的 width()height() 方法。

试试这个

 $.each(image, function () {
        var ratio = $(this).width()/$(this).height();

        if (ratio > 1) {
          $(".class1").addClass("added_1");
        }
        else if (ratio < 1) {
          $(".class1").addClass("added_2");
        }
   });

  image.src = image_url;

关于jquery 只检查页面上一张图片的比率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29696179/

相关文章:

javascript - 单击其他按钮后使按钮处于事件状态

css - 尝试开始使用 Bourbon/SASS(以及如何在 Adob​​e Brackets 中编译)

css - 背景图片和滚动条

javascript - 将 localstorage 变量发送到 PHP

php - 如何使用 AJAX 通过 jquery 上传文本值以及 dropzone 值?

javascript - 将jquery移入js文件导致引用错误和类型错误

php - Chrome 预览的预设打印设置

css - 我不知道如何解决这个 Bootstrap 问题

html - 如何在顶部覆盖内容的情况下填充背景图像的一半宽度?

background-image - 圆 Angular 与背景图像变色