2012-01-15 3 views
2

iframe의 크기를 조정하는 방법에 대해 많은 질문을했지만 그 중 모두는 외부 URL에 액세스 할 수 없습니다. 이 경우 나는 그렇다. head 태그에 스크립트를 삽입 할 수 있습니다. 나는 iframe이 (내가 개폐 프레임 태그가 잘못 알고가 포함 된 메인 페이지의 헤더에 삽입이 스크립트를 사용하려고했다 - 그것은 내가 그들을 떠나게하지 않을 :iframe 크기 조정 - 외부 URL 코드에 대한 액세스 권한이 있습니다.

iframe id="frame-one" scrolling="no" frameborder="0" src="yoursitehereexample"  onload="FrameManager.registerFrame(this)" /iframe 

을하고있는 이것을 JS 헤더 (링크 FrameManager.js 파일) 다음

var FrameManager = 
{ 
currentFrameId : '', 
currentFrameHeight : 0, 
lastFrameId : '', 
lastFrameHeight : 0, 
resizeTimerId : null, 

init : function() 
{ 
    if (FrameManager.resizeTimerId == null) 
    { 
     FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 500); 
    } 
}, 

resizeFrames : function() 
{ 
    FrameManager.retrieveFrameIdAndHeight(); 

    if ((FrameManager.currentFrameId != FrameManager.lastFrameId) || 
     (FrameManager.currentFrameHeight != FrameManager.lastFrameHeight)) 
    { 
     var iframe = document.getElementById(FrameManager.currentFrameId.toString()); 

     if (iframe == null) return; 

     iframe.style.height = FrameManager.currentFrameHeight.toString() + "px"; 

     FrameManager.lastFrameId = FrameManager.currentFrameId; 
     FrameManager.lastFrameHeight = FrameManager.currentFrameHeight; 
     window.location.hash = ''; 
    } 
}, 

retrieveFrameIdAndHeight : function() 
{ 
    if (window.location.hash.length == 0) return; 

    var hashValue = window.location.hash.substring(1); 

    if ((hashValue == null) || (hashValue.length == 0)) return; 

    var pairs = hashValue.split('&'); 

    if ((pairs != null) && (pairs.length > 0)) 
    { 
     for(var i = 0; i < pairs.length; i++) 
     { 
      var pair = pairs[i].split('='); 

      if ((pair != null) && (pair.length > 0)) 
      { 
       if (pair[0] == 'frameId') 
       { 
        if ((pair[1] != null) && (pair[1].length > 0)) 
        { 
         FrameManager.currentFrameId = pair[1]; 
        } 
       } 
       else if (pair[0] == 'height') 
       { 
        var height = parseInt(pair[1]); 

        if (!isNaN(height)) 
        { 
         FrameManager.currentFrameHeight = height; 
         FrameManager.currentFrameHeight += 15; 
        } 
       } 
      } 
     } 
    } 
}, 

registerFrame : function(frame) 
{ 
    var currentLocation = location.href; 
    var hashIndex = currentLocation.indexOf('#'); 

    if (hashIndex > -1) 
    { 
     currentLocation = currentLocation.substring(0, hashIndex); 
    } 

    frame.contentWindow.location = frame.src + '?frameId=' + frame.id + '#' + currentLocation; 
} 
}; 

window.setTimeout(FrameManager.init, 300); 

... 내가 링크로 프레임 페이지 헤더 ResizeFrame.js에 넣고 :

//orig frame mgr script 
$.getScript("http://www.yoursitehereexamle.com/js/FrameManager.js", function(){ 

}); 


// external heights load 

function publishHeight() 
{ 
if (window.location.hash.length == 0) return; 

var frameId = getFrameId(); 

if (frameId == '') return; 

var actualHeight = getBodyHeight(); 
var currentHeight = getViewPortHeight(); 

if (Math.abs(actualHeight - currentHeight) > 15) 
{ 
    var hostUrl = window.location.hash.substring(1); 

    hostUrl += "#"; 
    hostUrl += 'frameId=' + frameId; 
    hostUrl += '&'; 
    hostUrl += 'height=' + actualHeight.toString(); 

    window.top.location = hostUrl; 
} 
} 

function getFrameId() 
{ 
var qs = parseQueryString(window.location.href); 
var frameId = qs["frameId"]; 

var hashIndex = frameId.indexOf('#'); 

if (hashIndex > -1) 
{ 
    frameId = frameId.substring(0, hashIndex); 
} 

return frameId; 
} 

function getBodyHeight() 
{ 
var height; 
var scrollHeight; 
var offsetHeight; 

if (document.height) 
{ 
    height = document.height; 
} 
else if (document.body) 
{ 
    if (document.body.scrollHeight) 
    { 
     height = scrollHeight = document.body.scrollHeight; 
    } 
    if (document.body.offsetHeight) 
    { 
     height = offsetHeight = document.body.offsetHeight; 
    } 

    if (scrollHeight && offsetHeight) 
    { 
     height = Math.max(scrollHeight, offsetHeight); 
    } 
} 

return height; 
} 

function getViewPortHeight() 
{ 
var height = 0; 

if (window.innerHeight) 
{ 
    height = window.innerHeight - 18; 
} 
else if ((document.documentElement) && (document.documentElement.clientHeight)) 
{ 
    height = document.documentElement.clientHeight; 
} 
else if ((document.body) && (document.body.clientHeight)) 
{ 
    height = document.body.clientHeight; 
} 

return height; 
} 

function parseQueryString(url) 
{ 
url = new String(url); 
var queryStringValues = new Object(); 
var querystring = url.substring((url.indexOf('?') + 1), url.length); 
var querystringSplit = querystring.split('&'); 

for (i = 0; i < querystringSplit.length; i++) 
{ 
    var pair = querystringSplit[i].split('='); 
    var name = pair[0]; 
    var value = pair[1]; 

    queryStringValues[name] = value; 
} 

return queryStringValues; 
} 
// window load 
window.onload = function(event) 
    { 
     window.setInterval(publishHeight, 300); 
    } 

운 좋게도 작동하지 않습니다. 어디서 잘못되었는지 볼 수있는 사람이 있습니까? iframe은 여전히 ​​나타나지만 크기가 조정되지 않습니다. 많은 감사!

답변

0

다음은 외부 웹 사이트에서 iframe의 크기를 조정하는 코드입니다. iframe 코드가있는 상위 페이지와 외부 웹 사이트에도 코드를 삽입해야하므로 외부 웹 사이트를 수정할 수있는 권한이없는 경우 작동하지 않습니다.

  • 지역 (iframe이) 페이지 : 당신이 "신체 온로드"모든 내용을 유지하는 "DIV"을 필요 단지 코드가
  • 원격 (외부) 페이지를 니펫을 삽입합니다. 당신은 트위터 나 페이스 북 플러그인과 같은 다른 임베디드 코드 문제를 방지하기 위해 "FRM"접두어가 필요

    <IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME> 
    
    <SCRIPT> 
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; 
    var eventer = window[eventMethod]; 
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"; 
    eventer(messageEvent,function(e) { 
        if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px'; 
    },false); 
    </SCRIPT> 
    

    : 지역

: 그리고 몸은 "0 마진"으로 스타일을 지정할 필요가있다. 일반 페이지가있는 경우 두 페이지 (스크립트 및 onload)에서 "if"및 "frm"접두어를 제거 할 수 있습니다.

원격 :

당신은 jQuery를이 "진짜"페이지 높이에 대해 수행해야합니다. body.scrollHeight 또는 related를 사용하여 높이를 낮추면 (높이가 낮을수록 높이가 낮아짐) 문제가 생길 수 있으므로 순수 JavaScript로 수행하는 방법을 알지 못합니다. 어떤 이유로 든 항상 가장 큰 높이 (사전 치수 변경)를 반환합니다.

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0"> 
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT> 
<DIV ID="master"> 
your content 
</DIV> 

따라서 상위 페이지 (iframe)의 기본 높이는 1px입니다. 스크립트는 iframe에서 "message/event 대기"를 삽입합니다. 메시지 (게시물 메시지)가 수신되고 첫 번째 3 개의 문자가 "frm"인 경우 (위에서 언급 한 문제를 방지하기 위해) 네 번째 위치에서 번호를 가져오고 'px '단위를 포함하여 iframe 높이 (스타일)를 설정합니다.

외부 사이트 (iframe에로드 됨)는 "frm"및 메인 div의 높이 (이 경우 ID는 "master")로 부모 (오프너)에게 "메시지를 보냅니다". postmessage의 "*"는 "모든 출처"를 의미합니다.

희망이 도움이됩니다. 내 영어로 미안해.

관련 문제