JQuery FancyBox With IFrame Issue (PHP)

2019-08-01 22:35发布

问题:

Hi I am trying to use FancyBox in a page I am making containing videos, Like a Gallery of videos, my intention is to be linking YouTube videos in.

The issue I get is it just links through to the age link a normal a tag would do and nothing else happens.

This is the code I am using to generate the videos.

    while ($row = mysqli_fetch_assoc($result)){
         echo "
             <div class='portalVideo'>
                  <a class='fancybox fancybox.iframe' href='https://www.youtube.com/watch?v=DB7jsjt4Uec'>
                      <h3>
                          <strong>".$row["VideoName"]."</strong>
                      </h3>
                  </a>
             </div>";
    }

All my video link are pulled from a database and then displayed on the page as a a text link which "should" open the iframe when clicked. The only aspect that doesn't work is the iframe. everything else pulls and displays correctly.

I have included the files correctly and they link correctly to the resources. just for consolidation see below.

<script type="text/javascript" src="scripts/jquery.fancybox-1.3.4.pack.js"></script>
<link rel="stylesheet" type="text/css" href="css/jquery.fancybox-1.3.4.css">

Based off this stack overflow post I have tried to fix it. My code does contain the jquery below just under the head tags.

<script type="text/javascript">
    $(document).ready(function() {
        $('a.fancybox').fancybox();
    });
</script>

回答1:

You have two (none PHP related) issues :

1). This youtube format :

https://www.youtube.com/watch?v=DB7jsjt4Uec 

.... is not supported inside an iframe because most likely it contains a DENY X-Frame-options response header. You may need to convert it into an embed format like :

https://www.youtube.com/embed/DB7jsjt4Uec 

2). The special class fancybox.iframe is only supported in fancybox v2.x but you seem to be using fancybox v1.3.x. So you rather use the class iframe or add the API option

type: "iframe"

... to your custom fancybox initialization script.

Since you are pulling the video links from a database, the good news is you don't have to change anything in your PHP code but only in your jQuery code like :

jQuery(document).ready(function ($) {
    $(".fancybox").each(function (i) {
        // change links on the fly to embed format
        this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'embed/') + "?autoplay=1";
    }).fancybox({
        // API options
        type: "iframe" // needed for videos embed format
    });
}); // ready

Notice I am adding ?autoplay=1 to the new href but that's optional if you want your videos autoplay once in fancybox's iframe.