我在页面上有几个 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/