gpt4 book ai didi

javascript - Firefox 和 IE 对待图像对象的方式与 Webkit 有何不同?

转载 作者:行者123 更新时间:2023-12-02 18:43:04 25 4
gpt4 key购买 nike

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

这是函数:

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 中则不然。问题在于 t.height 和 t.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,'');

关于javascript - Firefox 和 IE 对待图像对象的方式与 Webkit 有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16687024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com