Выберите элемент iframe BODY в вызове лайтбокса - PullRequest
1 голос
/ 01 февраля 2012

это то, как они определили лайтбокс на работе

$(".lightbox873x560").colorbox({width:"845", height:"555", resize:false, iframe:true, scrolling:"no", opacity:"0.65"});
$(".lightboxGallery").colorbox({width:"845", height:"555", resize:false, iframe:true, scrolling:"no", opacity:"0.65"});

и т. Д.

И это то, что я предлагаю

$(".lightboxCustom").colorbox({
        width: $(this).attr('lWidth'), height: $(this).attr('lHeight'), resize:false, iframe:true, scrolling:"no", opacity:"0.65"

});

таким образом, атрибутыlWidth, lHeight будет определять размеры colorbox,

проблема заключается в том, что загруженный компонент в теле будет иметь другой предопределенный класс , который будет фиксировать лайтбоксСОДЕРЖАНИЕ ширина ..

Так как я могу удалить это?

я видел, что colorbox получает эти дополнительные параметры:

$(".lightboxCustom").colorbox({
        width: $(this).attr('lWidth'), height: $(this).attr('lHeight'), resize:false, iframe:true, scrolling:"no", opacity:"0.65",
        onOpen:function(){ alert('onOpen: colorbox is about to open'); },
        onLoad:function(){ alert('onLoad: colorbox has started to load the targeted content'); },
        onComplete:function(){ alert('onComplete: colorbox has displayed the loaded content'); }
});

Так в чемметод?Полное, верно?и как я могу найти / выбрать тело ??

пытается с:

onComplete:function(){
    console.log( $('#cboxIframe').length ); 
    console.log( $('#colorbox #cboxWrapper #cboxLoadedContent iframe').length ); 

}

но оба журнала 0 и является классом, который имеет iframe ..

РЕДАКТИРОВАТЬ

На данный момент это самое близкое, что у меня было:

$(".lightboxCustom").each(function(){
        $(this).colorbox({width: $(this).attr('lWidth'), height: $(this).attr('lHeight'), resize:false, iframe:true, scrolling:"no", opacity:"0.65",fastIframe:false,

            onComplete:function(){

                $(document).bind('cbox_complete',function(){
                        var iframe = $('#colorbox div#cboxWrapper div div#cboxContent div#cboxLoadedContent iframe#cboxIframe');
                                                                                       var body = iframe.contents().find('body');


                        console.log(iframe.length); /// ---> 1!!
                                            console.log(body.lenght);   /// ---> 1 :(
                                            /*But the problem is that this is empty*/
                                            alert(body.attr('class')); /*when its not*/
                })
            }

        });
});

Ответы [ 4 ]

2 голосов
/ 01 февраля 2012

Как предложено здесь , попробуйте присоединить ваш код к событию загрузки для содержимого iframe:

onComplete:function(){
    $("#cboxLoadedContent iframe").load(function(){
        console.log( $(this).length ); 
    });
}

РЕДАКТИРОВАТЬ:

Я провел немного больше тестирования иудалось получить body.length для возврата 1. Сначала убедитесь, что ваш документ и iframe соответствуют той же политике происхождения .См. этот вопрос для более подробной информации и обходного пути, если это необходимо.

Во-вторых, я переместил bind () в $ (document) .ready (), укоротил селектор, изменил iframe # cboxIframe на iframe.cboxIframe и добавил .contents () перед .find для iframe:

$(".lightboxCustom").each(function(){
    $(this).colorbox({width: $(this).attr('lWidth'), height: $(this).attr('lHeight'), resize:false, iframe:true, scrolling:"no", opacity:"0.65",fastIframe:false});
});
$(document).bind('cbox_complete',function(){
    var iframe = $('iframe.cboxIframe');
    var body = iframe.contents().find('body');
    console.log(iframe.length); /// ---> 1!!
    console.log(body.length);   /// ---> 1!! :)
});

Это работает для вас сейчас?

0 голосов
/ 29 февраля 2012

Если iframe src находится в одном домене, порте и протоколе, вы можете получить к нему доступ.Проблема в том, что вы не знаете, когда iframe доступен или готов к изменению.

События, встроенные в colorbox, ничего не гарантируют.Поэтому, если в colorbox нет «безопасного» события, которое срабатывает, когда iframe готов, вам, вероятно, нужно выполнить свою собственную проверку.

Браузеры имеют разные способы обработки этого, но самый безопасный способ - это, вероятно, проверитьдля BODY внутри этого iframe, а также наличия элементов в BODY, мы точно знаем, что он загружен (в противном случае вы можете получить поддельное тело в chrome).

Я сделал быстрый прототип здесь:http://jsfiddle.net/pfg3B/

Это выглядит примерно так:

// some local stuff for later use
var $colorbox = $('#colorbox'),
    tid, $body, $ibody,
    find = function() {
        $ibody = $colorbox.find('iframe').contents().find('body');
        // also make sure that there are elements in the body
        return $ibody.children('*').length ? $ibody : [];
    };

// attach a colorbox complete handler
$(document).bind('cbox_complete', function(e) {
    // the iframe doesn’t exist yet, we need to start a loop
    tid = setInterval(function() {
       $body = find();
        if($body.length) {
            // the iframe is found, clear the timer and access the body
            clearInterval(tid);
            // do something with $body, remove class or whatever
            $body.html('Yo!');
        }
    },10);
});

// apply the colorbox
$('.lightbox873x560').colorbox({
    ​​​​​​iframe: true,
    width: 100, // use your own lwidth if you like, this is just a test
    height: 100
});​
0 голосов
/ 27 февраля 2012

То, что они регистрируют 0, говорит о том, что вы выбираете правильные элементы, но либо измеряете не то, либо измеряете слишком рано. Способ, которым я занимался в прошлом, - это вызов функции из iFrame после загрузки документа. Итак, используя jQuery:

На странице, загруженной в iframe

$(function() { // or you could/should use teh load event, particularly if the lightbox contains images
   window.parent.yourNamespace.setColorBoxToIframe(yourNameSpace.getDocumentHeight());
});

На всех ваших страницах

var yourNameSpace = {
    setColorBoxToIframe: function(height) {
        // do the stuff in here that you were doing in your colorbox onLoad event before
    },
    getDocumentHeight: function () { // Can't remember why this is so hacky, but there must've been some reason I wrote it like this
      if (document.compatMode == 'CSS1Compat') {
         return document.body.offsetHeight;
      } else {
         if ($.browser.msie)
            return document.body.scrollHeight;
         else 
            return Math.max($(document).height(), $(document.body).height());
      }
    } 
  }
0 голосов
/ 01 февраля 2012
$(".lightboxCustom").colorbox({
        width: $(this).attr('lWidth'), height: $(this).attr('lHeight'), resize:false, iframe:true, scrolling:"no", opacity:"0.65"

});

Эта идея хороша, здесь есть лишь небольшое недоразумение о том, как контекст выполнения (значение этого) работает в JavaScript / jQuery.

Попробуйте вместо этого:

$(".lightboxCustom").each(function(){
    $(this).colorbox({width: $(this).attr('lWidth'), height: $(this).attr('lHeight'), iframe:true, scrolling:"no", opacity:"0.65"});
});
...