我怎么能说“;如果宽度>高度“;那么“;这样做"使用jQuery

How can I say "if width > height" then "do this" with jQuery?

本文关键字:那么 这样做 高度 使用 jQuery quot 怎么能 如果 gt      更新时间:2023-09-26

我有一些元素。页面上它们的数量不断变化,请记住这一点。

该元素名为.portalimg。我需要说,如果是width > height,请将其width设置为125px。如果是height > width,则将height设置为125px。

这是我的:

$('.portalimg').each(function() {
  var pimgw = $(this).width();
    var pimgh = $(this).height();
    if (pimgw > pimgh) {
        $(this).css('width','125px')
    } else {
        $(this).css('height','125px')
    }
});

编辑:它提醒成功,但不应用width&height。我哪里错了?

第2版:用下面最干净的代码更新了代码。这仍然只限制高度属性,即使图像更高也会更宽。看看:

http://jacksongariety.com/gundoglabs/

第三版:问题是它们都返回0。如果我有一个警报,比如pimgw或pimgh的值,它总是0。

第4版:终于通过缓存获得了最好、最干净的代码,即使它从缓存中绘制图像,它也会始终正确加载:

$(function(){
    $('.portalimg').ready(function(){
        $('.portalimg').fadeTo(0,1).each(function(index) {
            var a = $(this);
            if (img.width() > a.height()) {
                a.css('width','135px')
            } else {
                a.css('height','125px')
            }
        });
    });
});

如果portalimg类有多个元素,您可以简单地使用.each迭代器:http://api.jquery.com/each/

$(function() {
    $('.portalimg').each(function(index) {
        var img = $(this);
        if (img.width() > img.height()) {
            img.css('width','125px')
        } else {
            img.css('height','125px')
        }
    });
}

$('.portalimg').each(function() {
  var pimgw = $(this).width();
    var pimgh = $(this).height();
    if (pimgw > pimgh) {
        $(this).css('width','125px')
    } else {
        $(this).css('height','125px')
    }
});

这个怎么样:

$('.portalimg').each(function() {
    (($(this).width() > $(this).height())
    && ($(this).css('width','125px')) )
    || ($(this).css('height','125px'))
});

http://jsfiddle.net/DerekL/Qx4jF/

您的循环错误,应该使用

pimg = $('.portalimg').each( function() {;
    alert("success")
    var pimgw = $(this).width();
    var pimgh = $(this).height();
    if (pimgw > pimgh) { 
        $(this).css('width','125px')
    } else {
        $(this).css('height','125px')
    }
});

这将对文档中类为".portalimg"的所有find对象调用一个函数。

$('.portalimg').each(function() { var
    img = $(this),
    w = img.width(),
    h = img.height(),
    toModify = w > h ? 'width' : 'height';
    img.css(toModify, '125px');
}

可以试试这个。其他答案都很好。for和body的语法出现错误。你是说#body还是.body?

$(".portalimg").each(function(){ 
    var pimgw = $(this).width(),
        pimgh = $(this).height();
    if (pimgw > pimgh) {
        $(this).css('width','125px')
    }else{
        $(this).css('height','125px')
    }
});

相关文章: