fotorama: can't get the API object (undefined)

谁说我不能喝 提交于 2021-01-05 11:59:16

问题


I'm using Fotorama 4.5.0 (Rails gem) and I have a problem with getting the API object.

On page load Fotorama is in hidden div. It opens in modal on click.
Here is the code (coffee):

$objects = $('*[rel="fotorama"]')
$fotorama_div = $('.fotorama')

$fotorama_div
.on('fotorama:showend', (e, fotorama, extra) ->
  // resizing fotorama
).fotorama()
fotorama = $fotorama_div.data('fotorama')
console.log(fotorama) // here is undefined

$objects.on 'click', ->
  // finding index of an image
  modal.open({content: $('#fotorama-container')})
  fotorama.show(index) // index is ok

With this code fotorama object is always undefined.
Ok, I added if with check:

$objects = $('*[rel="fotorama"]')
$fotorama_div = $('.fotorama')

$fotorama_div
.on('fotorama:showend', (e, fotorama, extra) ->
  // resizing fotorama
).fotorama()
fotorama = $fotorama_div.data('fotorama')
console.log(fotorama) // here is undefined

$objects.on 'click', ->
  // finding index of an image
  modal.open({content: $('#fotorama-container')})
  if typeof fotorama == "undefined"
    fotorama = $fotorama_div.data('fotorama')
    console.log(fotorama) // here is undefined after the first click on object
  fotorama.show(index) // index is ok

After the first click on object — fotorama is still undefined, but after I'm closing a modal and doing the second click — I get fotorama object and everything works as expected.

And when I doing $fotorama_div.data('fotorama') in console, it works.

How can I get fotorama object on page load?


回答1:


I was having the exact same problem - loading fotorama in a div gave "undefined" in console, only after showing the div again the fotorama object was loaded correctly.

I found the cause of this was loading fotorama in an object with "display: none;" css styling. I dont know why but if fotorama loads in something that is hidden then it breaks.

I dont know any RoR but my sugestion would be to first show the modal, then load fotorama $fotorama_div.fotorama() after the modal is opened.




回答2:


I had the same problem and found the reason why it returns undefined.
If the $fotorama_div has style="display: none;" attribute then $fotorama_div.data('fotorama') will return undefined.

So the solution is to remove this attribute style="display: none;" before you run $fotorama_div.data('fotorama').

$fotorama_div.show().data('fotorama');

If it still returns undefined then check if any parents of $fotorama_div has display: none css.

let hiddenParents = $fotorama_div.parents().filter(function() { 
    return $(this).css('display') == 'none';
});
hiddenParents.show();
let fotorama = $fotorama_div.data('fotorama');
hiddenParents.hide();
// Now enjoy with your fotorama from here.


来源:https://stackoverflow.com/questions/23211016/fotorama-cant-get-the-api-object-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!