0

这段代码:

$('#ad img').each(function(){
    if($(this).width() > 125){
        $(this).height('auto');
        $(this).width(125);
    }
});

在 Firefox 上正常工作,但在 Chrome 上不能正常工作。内部的img标签#ad由 限制height,但如果这使它们太宽,我需要限制宽度。有没有更好的方法可以在所有浏览器上运行?

图片的html如下:

<img src='http://easyuniv.com/img/ads/".$ad['img']."' height='40px'>
4

4 回答 4

3

你可以在没有 javascript 的情况下实现这一点。在 css 中使用它:

#ad img {
    width: 125px;
    height: auto;
    overflow: hidden;
}
于 2012-11-16T04:13:26.673 回答
2

我怀疑困扰你的是图像负载的可变性。如果图像本身在您的代码运行时尚未加载,则其宽度将为 0。您可能希望尝试使用加载处理程序以及运行现有代码以确保图像大小正确。注意:您需要使用现有代码来处理在添加加载处理程序之前加载图像的情况。

$(function() {
    $('#ad img').on('load', function() {
          resize(this);
    }).each( function() {
          resize(this);
    });

    function resize(image) {
       var $image = $(image);
       if ($image.width() > 125) {
           $image.css( { height: 'auto', width: 125 } );
       }
    }
});
于 2012-11-16T04:34:28.427 回答
1

尝试:

$(window).load(function () {
    $('#ad img').each(function(){
        if($(this).width() > 125){
            $(this).height('auto');
            $(this).width(125);
        }
    });
});
于 2012-11-16T04:49:32.040 回答
0

你试过了吗:

        $('#ad img').each(function(){
        if($(this).width() > 125) {
            $(this).css('height', 'auto');
            $(this).css('width',125);
        }
    })
于 2012-11-16T04:15:24.250 回答