2011-11-15 2 views
2

동일한 도메인에서 iframe에 보유 된 이미지 수가 많지만 이미지에 클릭 기능을 적용하여 해당 클릭이 iframe에서 튀어 나오게하고 싶습니다. 부모 본문으로jQuery iframe 및 라이트 박스 효과

이상적으로 jQuery를 iframe 본문에 삽입하고 부모 본문에 삽입해야합니다.

나는이 문제에 대해 어떻게 생각할 수 있습니까?

+0

iframe의 콘텐츠가 기본 페이지와 동일한 도메인에 있습니까? http://stackoverflow.com/q/1654017/901048 – Blazemonger

+0

예, 모든 도메인이 동일합니다. – CLiown

답변

0

이 시도하지 : iframe이 문서에서 필요한

<!--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> 

없음 스크립트 것은 확실히 jQuery의 $ (선택) .each() 기능을보다 효율적으로 할 수있다. 희망이 도움이!

관련 문제