简体   繁体   中英

javascript working in firefox but not chrome

This code:

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

is working properly on Firefox but not Chrome. The img tags inside of #ad are constricted by height , but if this makes them too wide I need to restrain the width. Is there a better way to do this that would work on all browsers?

The html for the image is as follows:

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

You could achieve this without javascript. Use this in the css :

#ad img {
    width: 125px;
    height: auto;
    overflow: hidden;
}

I suspect what is biting you is the variability in image load. If the image itself hasn't loaded by the time your code runs, it will have width of 0. You might want to try using a load handler as well as running your existing code to ensure that the images are sized properly. Note: you'll need to use your existing code to handle the case where the image is loaded before the load handler is added.

$(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 } );
       }
    }
});

Try:

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

Did you try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM