Firefox和IE处理图像对象的方式与Webkit有什么不同?

In what way does Firefox and IE treat the image-object diffrent from Webkit?

本文关键字:Webkit 什么 方式 IE 处理 图像 对象 Firefox      更新时间:2023-09-26

我正在编写一个脚本,根据背景图像是横向的还是纵向的,为图像添加一个类。

函数如下:

function loadImg (mythis, callback) {
    var src = getUrl($(mythis).css('background-image'));

    var t = new Image();
    t.src = src;
    console.log(t.height);
    var height = t.height;
    var width = t.width;
    if(width > height){
        $(mythis).parent().addClass('panorama');    
        $(mythis).parent().parent().removeClass('smallpost');                    
}

这在Webkit中很好,但在Firefox或IE中就不行了。问题是。height和。width在这些浏览器中总是为零。此解决方案的一个挑战是,需要在运行函数之前加载图像。因为图像是背景图像,不在DOM中,所以我最终只是在脚本运行之前添加了延迟。我知道这有点罪恶,但在这种情况下确实是一个可以接受的解决方案。但我不确定这是否与我的问题有关。

javascript:美元(函数(){

    setTimeout(function(){
        var elems = $('.post .crop'), count = elems.length;
        $(elems).each(function(i){
            //Rezise image
            loadImg(this, function callback(){
            //Run masonry afte last image
            if (i = count-1){
                $('#content').imagesLoaded(function(){
                    $('#content').masonry({
                        itemSelector : '.post',
                        gutterWidth: 15,
                        columnWidth: 320
                    });
                });
            };

            });
        })
    },5000);
    //getImgSize('http://25.media.tumblr.com/83c73059a904b46afba332f26e33c5bd/tumblr_mmvwy7XjKq1sqsf7io1_500h.jpg')
    function getUrl(styling){
        styling = styling.replace('url(','').replace(')','');
        return (styling);
    }
    function loadImg (mythis, callback) {
        var src = getUrl($(mythis).css('background-image'));

        var t = new Image();
        t.src = src;
        console.log(t.height);
        var height = t.height;
        var width = t.width;
        if(width > height){
            $(mythis).parent().addClass('panorama');    
            $(mythis).parent().parent().removeClass('smallpost');                    
    }
    callback();

    }
});

您看到的差异通常与图像的缓存状态有关:如果图像已经可用,则可以立即知道尺寸。

您需要处理load事件:

var t = new Image();
t.onload = function(){
   var height = t.height;
   var width = t.width;
   if(width > height){
       $(mythis).parent().addClass('panorama');    
       $(mythis).parent().parent().removeClass('smallpost');
   }  
};
t.src = src;
编辑:

你有另一个问题在你的getUrl函数:它不删除引号,一些浏览器可能会添加到样式。

改变
styling = styling.replace('url(','').replace(')','');

styling = styling.replace('url(','').replace(')','').replace(/"/g,'');