how to access an iframe and affect it with jQuery

2020-05-01 07:07发布

问题:

I'm trying to slideDown an iframe embedded into my document. The iframe contains another website. I've looked at this thread so far:

Can we do fade in and fade out in iframes

but the technique of increasing opacity does not apply to slide animations AND it does not address the problem of changing the iframe's css. This is my code so far (the iframe's id is "sketchpad"):

var skpad = document.getElementById('sketchpad').contentDocument;
    var skpad$ = $(skpad);
    $('.sketchBtn').bind('click',
        function() {
            alert(skpad$);
            skpad$.slideDown(300);
        }
    );

I've also tried this:

skpad$.css({
            display:'block'
            })
            .animate({
            opacity:'1.0',              
            },300);

The bottom is not a slide down, but i was just trying to see if it would work. It didn't. Any ideas?

回答1:

If you're looking to do this cross-domain, it is only possible if you can control the content on the iframe's SRC. But then, I'm guessing, if you could control the content of the iframe's SRC you would have just written the slideDown code in there, wouldn't you have?

Javascript has a Same-Origin policy in which javascript on the outer page cannot access the contentWindow or DOM (or global state) of the iframe page if it does not share the Same-Origin. Same origin in this case means that host+domain matches up, so for example www.domain.com is different than static.domain.com. Same origin also means the protocols match up.

If by chance you happen to control the content of the iframe, you could simply add the slideDown to it on DOM Ready. If you wanted to get really fancy you could implement window.postMessage to signal the child Iframe when to scroll down, but that would just be overkill likely.

Your best bet is to mess with animating the <iframe> tag itself and leaving the inner content alone. Perhaps there is a track you could do where a <div> the same color as the background of the parent page scrolls down over top of the <iframe> effectively simulating a scrollDown?