Fix an element inside an iframe in the center of t

2019-08-23 12:53发布

问题:

I have an iframe embedded inside a fan page of FB, and I want to show a fixed box (like a dialog box) at the center of the screen.

How can I do that?

UPDATE

Look at Work For Us app:

http://www.facebook.com/DiscoverIntel?ref=nf&sk=app_404596412628

When I click in the green button behind (named "Apply for this position") it always shows the "Thank you" dialog at the center of the screen.

回答1:

I just got the same problem today. The solution is you just need to get scroll position of the viewport from the parent of the iframe which is Facebook URL. So, Facebook has provided JavaScript SDK for it already.

http://developers.facebook.com/docs/reference/javascript/FB.Canvas.getPageInfo/

You can use clientHeight, clientWidth , scrollTop and scrollLeft to calculate the center position.



回答2:

You can't. The iframe fills a div element that's position style is set to relative. It's impossible and for good reason too. What if the center of the screen isn't over your iframe? Facebook doesn't want you doing anything crazy and messing with the presentation of the page itself (i.e. hiding advertisements, making a fake Facebook-looking elements, etc.).

But if you are looking to center an element within the iframe, you can do something like this:

<!DOCTYPE html>
<html>
    <head>
        <title>Centering an element with CSS</title>
        <style type="text/css">
            #center_container {
                left: 50%;
                position: fixed;
                top: 50%;
            }
            #center {
                border: 1px dashed #000; /* added to show size and position of element */
                height: 100px;
                left: -100px; /* -0.5 * width */
                position: absolute;
                top: -50px; /* -0.5 * height */
                width: 200px;
            }
        </style>
    </head>

    <body>
        <div id="center_container">
            <div id="center">This tag is centered.</div>
        </div>
    </body>
</html>

Otherwise, you will have to stick to using JavaScript's popup box functions: alert(), confirm(), and prompt().