问题
So I am attempting to combine jQuery Masonry plugin ( from : http://masonry.desandro.com/ ) with modernizr to kill masonry when at low resolutions so that my divs revert to a centered partial width layout. I will admit that my javascript skills are still in developing, but I figured the community might be able to help me out on this one.
At resolutions below 768 px I would like masonry to be destroyed if active and when at larger resolutions I would like it to execute if not already running. Presently everything is working perfectly except I am getting this error in my console:cannot call methods on masonry prior to initialization; attempted to call 'destroy'. This is the code that I have that handles this task.
$(window).load( function() {
$('#masonry').masonry({
transitionDuration: 10,
columnWidth:'.sizer',
});
if(Modernizr.mq('screen and (max-width:767px)') && $('#masonry').masonry) {
$('#masonry').masonry('destroy');
}
});
$(document).ready(function() {
function doneResizing() {
if(Modernizr.mq('screen and (min-width:768px)')) {
// action for screen widths including and above 768 pixels
$('#masonry').masonry({
transitionDuration: 10,
columnWidth:'.sizer',
});
}
else if(Modernizr.mq('screen and (max-width:767px)') && $('#masonry').masonry) {
// action for screen widths below 768 pixels
$('#masonry').masonry('destroy');
}
}
var id;
$(window).resize(function() {
clearTimeout(id);
id = setTimeout(doneResizing, 0);
});
doneResizing();
});
So the only way that I could figure out how to fix this is by declaring a boolean variable globally so that I could use it between the two areas of code. I have read this is bad practice, but as this is the only use for this variable, and there are no possible security concerns, should I actually still not do this?
//init masonry
$(window).load( function() {
$('#masonry').masonry({
transitionDuration: 10,
columnWidth:'.sizer',
}
);
window.masonryIsActive = true;
if(Modernizr.mq('screen and (max-width:767px)')) {
$('#masonry').masonry('destroy');
window.masonryIsActive = false;
}
});
$(document).ready(function() {
function doneResizing() {
if(Modernizr.mq('screen and (min-width:768px)')) {
// action for screen widths including and above 768 pixels
$('#masonry').masonry({
transitionDuration: 10,
columnWidth:'.sizer',
});
window.masonryIsActive = true;
}else if(Modernizr.mq('screen and (max-width:767px)') && window.masonryIsActive == true) {
// action for screen widths below 768 pixels
$('#masonry').masonry('destroy');
window.masonryIsActive = false;
}
}
回答1:
You have to initialize masonry whenever you call any method in masonry Like,
$('#masonry').masonry().masonry('destroy');
$('#masonry').masonry().masonry('remove');
来源:https://stackoverflow.com/questions/26068935/cannot-call-methods-on-masonry-prior-to-initialization-attempted-to-call-destr