我正在寻找一种在浏览器中完全呈现图像后触发某些代码的方法。我正在使用同位素砌体http://isotope.metafizzy.co/插件,它使用元素的高度来计算砌体布局,但遗憾的是onShow
和onRender
事件在图像完全加载之前过早发生。渲染,因此同位素计算错误的高度。我尝试使用https://github.com/desandro/imagesloaded来帮助解决问题,但代码仍然过早发布。有什么建议我可以让ItemView等到图像完全显示在DOM中吗?
List.Recipe = Marionette.ItemView.extend({
template: '#recipe-list-item',
model: this.model,
className: 'isotope--recipe',
serializeData: function () {
var data = this.model.toJSON()
return data
},
onShow: function () {
$(this).imagesLoaded().done( function () {
$('.isotope--recipes').isotope({
itemSelector: ".isotope--recipe",
masonry: {
gutter: 25
}
})
})
}
})
我也试过
List.Recipe = Marionette.ItemView.extend({
template: '#recipe-list-item',
model: this.model,
className: 'isotope--recipe',
serializeData: function () {
var data = this.model.toJSON()
return data
},
initialize: function () {
Marionette.bindEntityEvents(this, this, this.events)
},
triggers: {
'load img': 'image:loaded'
},
events: {
'image:loaded': 'masonryise'
},
masonryise: function () {
$('.isotope--recipes').isotope({
itemSelector: ".isotope--recipe",
masonry: {
gutter: 25
}
})
}
})
答案 0 :(得分:0)
看来,加载事件在事件哈希中不能像预期的那样suggested here起作用,因此您可以使用addEventListener这样的方式连接它们:
layout: function (container) {
var that = this;
if (that.layoutComplete) {
return;
}
if (!that.msnry) {
that.msnry = new Masonry(container,
{
gutter: 10,
itemSelector: '.item'
});
}
if (!that.images) {
that.images = Array.from(that.el.querySelectorAll(".masonry img"));
//load events don't seem to fire from the events hash so connect them manually
that.images.forEach((i) => i.addEventListener("load",
function(evt) {
that.layout();
}));
}
if (that.images.every(function (img) { return img.complete; })) {
that.layoutComplete = true;
//final layout once all finished
that.msnry.layout();
} else if (!that.firstLayoutComplete && that.images.slice(0, 10).every(function (img) { return img.complete; })) {
that.firstLayoutComplete = true;
//layout once first 10 are loaded to appear responsive
that.msnry.layout();
}
},
onShow: function () {
var container = this.el.querySelector('.masonry>div');
if (document.readyState === "complete") {
this.layout(container);
} else {
jQuery(window).on("load", function () {
this.layout(container);
});
}
}