2011-11-15 66 views
2

我有一個圖像保存在一個iframe,在同一個域,但我希望能夠應用點擊功能的圖像,以便當它的點擊它彈出的iframe和進入父母身體。jQuery的iframe和燈箱效果

理想情況下,我不想將jQuery插入到iframe正文中,只是將其存在於父體中。

任何人都可以想到我會如何去做這件事嗎?

+0

您的iframe與您的主頁在同一個域中的內容是?另請參見http://stackoverflow.com/q/1654017/901048 – Blazemonger

+0

是的,它們都位於同一個域中。 – CLiown

回答

0

試試這個:

<!--We'll be selecting our images from this frame--> 
<iframe id="img_from" src="path/to/same_origin_script.html"></iframe> 
<!--We'll be placing the image from the above frame here when the user clicks on it--> 
<span id="img_to"></span> 
<script type="text/javascript"> 
    window.onload = function() 
    { 
     //The iframe document 
     var f = document.getElementById('img_from').contentWindow.document; 
     //Register and add event listeners for each image in the iframe... You might want to narrow this down by using class name instead. 
     for (var i=0; i<f.getElementsByTagName('img').length; i++) 
     { 
      //To ensure that event listener is assigned appropriately 
      (function(i) 
      { 
       //Register an image from the iframe. 
       var img = f.getElementsByTagName('img').item(i); 
       //Add onclick event listener to the image that pulls it from the iframe and puts it in the parent document 
       img.onclick = function() 
       { 
        //Create a new image element 
        var newImg = document.createElement('img'); 
        //Give the new image a meaningful id 
        newImg.id = 'img_to-'+i; 
        //Assign source of clicked image to new image. You may want to use absolute linking in your iframe to avoid bad source links in the parent document. 
        newImg.src = img.src; 
        //Add the new image to the #image_to span in the parent document 
        document.getElementById('img_to').appendChild(newImg); 
        //Optional: remove the image from the iframe's DOM 
        img.parentNode.removeChild(img); 
        //Just in case the image is wrapped in a link, return false to avoid jumping to the href. 
        return false; 
       } 
       //Still making sure i behaves as expected... 
      }) (i); 
     } 
    } 
</script> 

沒有必要的iframe文檔中的腳本,可以確實地進行與jQuery的$(選擇)。每個()功能更有效。希望這可以幫助!