convert preload img to iframe

2019-09-13 01:53发布

问题:

$('<img />')
   .attr('src', val)
   .attr('width', "400")
   .load(function(){
      $('.showdata').append( $(this) );
   }
);

This works perfectly for images, how would this convert 1:1 to iframes? Here quick jsfiddle: http://jsfiddle.net/ET8Gw/

回答1:

Unlike Image objects, IFrames will not load until they are part of the DOM.

To get around this you can hide the element, add it to the DOM, and when the load event fires show it:

var val = "http://dumb.com/";
 $('<iframe />')
            .hide()
            .attr('src', val)
            .attr('width', "500")
            .load(function(){
                $(this).show();
            })
            .appendTo(".showdata");

http://jsfiddle.net/ET8Gw/1/



回答2:

var val = "http://inapcache.boston.com/universal/site_graphics/blogs/bigpicture/texas_drought_fires/bp1.jpg";
$('<iframe/>')
    .attr('src', val)
    .attr('width', "500")
    .appendTo($('.showdata'));

http://jsfiddle.net/ET8Gw/5/



回答3:

Try something like this:

$("<iframe></iframe>")
    .css("display":"none")
    .attr('src', val)
    .load( 
        function(){
            $(this).show();
        })
    .appendTo(".showData");

It will not work cross domain.



回答4:

I got it working doing this

var val = "http://inapcache.boston.com/universal/site_graphics/blogs/bigpicture/texas_drought_fires/bp1.jpg";

$('.showdata').append('<iframe src="' + val + '" width="400" height="200"><\/iframe>');

jsFiddle: http://jsfiddle.net/ET8Gw/22/