2011-08-23 159 views

回答

21

這對我有效。

var iframes = $('iframe'); 

$('button').click(function() { 
    iframes.attr('src', function() { 
     return $(this).data('src'); 
    }); 
}); 

iframes.attr('data-src', function() { 
    var src = $(this).attr('src'); 
    $(this).removeAttr('src'); 
    return src; 
}); 

jsFiddle

+1

因此,如果'src'被硬編碼在DOM的html中,請將其更改爲'data-src',然後根據需要將其更改爲'src'來加載內容?另外,我的事件不是基於滾動,而是點擊包含'div'的':target'。 – Steve

+0

@Max你明白了。 – alex

+0

Downvote的解釋呢? – alex

0

您可以始終將src屬性初始化爲about:blank,然後當點擊事件觸發時,將src屬性設置爲您要導航到的URL。

+0

iframe的src'在DOM的HTML中被硬編碼,並且不想通過用about:blank代替它來執行太多的DOM操作,然後用URL替換它(它需要被存儲爲一個變量)。 – Steve

0

你可以將src設置爲about:blank嗎?喜歡這個?

http://jsfiddle.net/MaUfH/

+0

iframe嵌入到頁面的HTML中並加載頁面,而您的示例將加載iframe onClick。這在我的情況下不起作用。 – Steve

3

一個similar question是最近使用的技術。我打電話Lazy Loading of iFrames公佈具體到基於引導,Twitter的標籤,這是我answered iFrame中。 js/jquery如下;看到完整的代碼,包括在小提琴或我到OP響應HTML標記:

<script> 
$('#myTabs').bind('show', function(e) { 

// identify the tab-pane 
paneID = $(e.target).attr('href'); 

// get the value of the custom data attribute to use as the iframe source 
src = $(paneID).attr('data-src'); 

//if the iframe on the selected tab-pane hasn't been loaded yet... 
if($(paneID+" iframe").attr("src")=="") 
{ 
    // update the iframe src attribute using the custom data-attribute value 
    $(paneID+" iframe").attr("src",src); 
} 
}); 
</script> 
0

如果你想這樣做,在WordPress

這裏是一個自動的,要求降低,解決

在WordPress插件形式

這裏是一個WordPress插件,您可以手動下載和通過WordPress插件庫安裝。我今天創建這個只是爲了處理這種情況。不需要對內容進行任何更改,只要在任何和所有內聯框架上激活,就會自動運行。

https://wordpress.org/plugins/lowermedia-iframes-on-demand/