jQuery FancyBox YouTube videos not working

后端 未结 2 438
不知归路
不知归路 2020-12-22 11:17

I have a situation whereby I cannot modify the HTML code for the anchor tag, with the exception of the \'href\' attribute. So adding a class to the anchor tag is not an opti

相关标签:
2条回答
  • 2020-12-22 11:53
    adding a class to the anchor tag is not an option
    

    That is not necessarily true since you can always add the class via jQuery like

    $('a[href*="youtube"]').addClass("fancybox")
    

    Anyway, personally I don't like to use the swf mode for youtube videos any more but iframe mode; that makes them easier to handle and cross-platform compatible (including iOS)

    What I would do is, using the .each() method :

    • convert every single href to embed format using javascript .replace()
    • bind each anchor to fancybox
    • set the new converted href using the fancybox href API option

    This is the code that works for both fancybox v1.3.4 or v2.x :

    (function ($) {
      $(document).ready(function(){
        $('a[href*=youtube]').each(function () {
            // convert youtube swf href to embed for iframe
            var thisHref =  this.href
                           .replace(new RegExp("watch\\?v=", "i"), 'embed/')
                           .replace(new RegExp("&", "i"), '?');
            // bind fancybox to each anchor
            $(this).fancybox({
                "padding" : 0,
                "type" : "iframe",
                // add trailing parameters to href (wmode)
                "href" : thisHref + "&wmode=opaque"
            }); // fancybox
        }); // each
      }); // ready
    })(jQuery);
    

    Notice that I added wmode=opaque, otherwise the close button will be behind the youtube video.

    See JSFIDDLE with version 1.3.4 ... or JSFIDDLE with v2.1.4

    0 讨论(0)
  • You have missed the doc ready handler inside the closure and there is no need for the e.preventDefault():

    (function ($) { 
       $(function(){
         $('a[href*="youtube"]').fancybox({
            'padding' : 0,
            'type' : 'swf',
            'href' : this.href.replace(/watch?v=/gi, 'v/'),
            'swf' : { 'wmode' : 'transparent', 'allowfullscreen' : 'true' }
         });    
      });
    })(jQuery);
    
    0 讨论(0)
提交回复
热议问题