Program Tip

IFRAME 및 iPad의 Safari, 사용자는 콘텐츠를 어떻게 스크롤 할 수 있습니까?

programtip 2020. 10. 29. 19:11
반응형

IFRAME 및 iPad의 Safari, 사용자는 콘텐츠를 어떻게 스크롤 할 수 있습니까?


Apple iOS mantra에 따르면 두 손가락으로 드래그하여 IFRAME의 내용을 스크롤 할 수 있어야합니다. 안타깝게도 iPad에서 최신 버전의 iOS를 실행하는 경우이 방법을 사용하여 스크롤하는 IFRAME이있는 단일 웹 사이트를 아직 찾지 못했습니다. 스크롤 막대도 나타나지 않습니다.

사용자가 모바일 Safari로 IFRAME의 콘텐츠를 스크롤해야하는 방법을 아는 사람이 있습니까?


iOS 5는 스크롤이 작동하도록 상위 div에 추가 할 수있는 다음 스타일을 추가했습니다.

-webkit-overflow-scrolling:touch


-webkit-overflow-scrolling:touch 답변에서 언급했듯이 실제로 가능한 해결책입니다.

<div style="overflow:scroll !important; -webkit-overflow-scrolling:touch !important;">
     <iframe src="YOUR_PAGE_URL" width="600" height="400"></iframe>
</div>

그러나 아래 이미지와 같이 iframe 내부에서 위아래로 스크롤 할 수없는 경우 여기에 이미지 설명 입력

이렇게 대각선 방향으로 두 손가락으로 스크롤 해 볼 수 있습니다.

여기에 이미지 설명 입력

이것은 실제로 제 경우에 효과가 있었으므로 아직 해결책을 찾지 못한 경우 공유하십시오.


iframe이 제대로 표시되고 스크롤되지 않는 것 같습니다. 개체 태그를 사용하여 iframe을 대체 할 수 있으며 두 손가락으로 콘텐츠를 스크롤 할 수 있습니다. 다음은 간단한 예입니다.

<html>
    <head>
        <meta name="viewport" content="minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;"/>
    </head>
    <body>
        <div>HEADER - use 2 fingers to scroll contents:</div>
        <div id="scrollee" style="height:75%;" >
            <object id="object" height="90%" width="100%" type="text/html" data="http://en.wikipedia.org/"></object>
        </div>
        <div>FOOTER</div>
    </body>
</html>

이것은 내 대답이 아니지만 대답이 굉장하고 문제를 완전히 수정했기 때문에 https://gist.github.com/anonymous/2388015 에서 복사했습니다 . 신용은 완전히 익명의 저자에게 돌아갑니다.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        if (/iPhone|iPod|iPad/.test(navigator.userAgent))
            $('iframe').wrap(function(){
                var $this = $(this);
                return $('<div />').css({
                    width: $this.attr('width'),
                    height: $this.attr('height'),
                    overflow: 'auto',
                    '-webkit-overflow-scrolling': 'touch'
                });
            });
    })
</script>

다른 게시물에서 언급했듯이 오버플로의 CSS 값 조합 : auto; & -webkit-overflow-scrolling : touch;

문제의 iframe과 상위 div 모두에 적용될 때 작동합니다.

비 터치 브라우저에서 이중 스크롤바의 불행한 부작용이 있습니다.

내가 사용한 해결책은 javascript / jquery를 통해 이러한 CSS 값을 추가하는 것입니다. 모든 브라우저에서 기본 CSS를 사용할 수있었습니다.

if (isSafariBrowser()){
    $('#parentDivID').css('overflow', 'auto');
    $('#parentDivID').css('-webkit-overflow-scrolling', 'touch');
    $('#iframeID').css('overflow', 'auto');
    $('#iframeID').css('-webkit-overflow-scrolling', 'touch');
}

isSafariBrowser ()는 다음과 같이 정의됩니다.

var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
var is_safari = navigator.userAgent.indexOf("Safari") > -1;

function isSafariBrowser(){
    if (is_safari){
        if (is_chrome)  // Chrome seems to have both Chrome and Safari userAgents
            return false;
        else
            return true;
    }
    return false;
}

이로 인해 내 애플리케이션이 iPad에서 작동 할 수있었습니다. 참고 1) 다른 iOS 시스템에서는 테스트되지 않았습니다. 2) 태블릿의 Android 브라우저에서는 테스트되지 않았으며 추가 변경이 필요할 수 있습니다.

(따라서이 솔루션은 완전하지 않을 수 있습니다)


아래 코드는 저에게 효과적입니다 ( http://dev.magnolia-cms.com/blog/2012/05/strategies-for-the-iframe-on-the-ipad-problem/ )에 대한 Christopher Zimmermann에게 감사드립니다. . 문제는 다음과 같습니다.

  1. 사용자에게 스크롤 할 수 있음을 알려주는 스크롤 막대가 없습니다.
  2. 사용자는 두 손가락 스크롤을 사용해야합니다.
  3. PDF 파일이 중앙에 있지 않습니다 (여전히 작업 중).

    <!DOCTYPE HTML>
    <html>
    <head>
      <title>Testing iFrames on iPad</title>
      <style>
      div {
        border: solid 1px green;
        height:100px;
      }
    
    .scroller{
        border:solid 1px #66AA66;
        height: 400px;
        width: 400px;
        overflow: auto;
        text-align:center;
    
    }
    </style>
    

    <table>
      <tr>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
      </tr>
      <tr>
      <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
      </tr>
    </table>
    <div> Here are some additional contents.</div>
    


iframe 스크롤링이 iPad에서 작동하도록하기 위해 제가 한 것입니다. 이 솔루션은 iframe 내부에 표시되는 html을 제어하는 ​​경우에만 작동합니다.

실제로 기본 iframe 스크롤을 끄고 대신 iframe 내부의 body 태그를 스크롤합니다.

main.html :

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container {
    position: absolute;
    top: 50px;
    left: 50px;
    width: 400px;
    height: 300px;
    overflow: hidden;
}
#iframe {
    width: 400px;
    height: 300px;
}
</style>
</head>
<body>

    <div id="container">
        <iframe src="test.html" id="iframe" scrolling="no"></iframe>
    </div>

</body>
</html>

test.html :

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { 
    overflow: auto; 
    -webkit-overflow-scrolling: touch; 
}
body {
    height: 100%;
    overflow: auto; 
    -webkit-overflow-scrolling: touch;
    margin: 0;
    padding: 8px;
}
</style>
</head>
<body>
</body>
</html>

원하는 경우 jQuery를 사용하여 동일한 작업을 수행 할 수 있습니다.

$("#iframe").contents().find("body").css({
    "height": "100%",
    "overflow": "auto", 
    "-webkit-overflow-scrolling": "touch"
});

이 솔루션을 사용하여 TinyMCE (워드 프레스 편집기)가 iPad에서 제대로 스크롤되도록했습니다.


이 기사를 기반으로 매우 기본적인 기능을 제공하는 다음 스 니펫을 모았습니다.

<div id = "container"></div>
<script>
function setPDFHeight(){ 
        $("#pdfObject")[0].height = $("#pdfObject")[0].offsetHeight;   
}   
$('#container').append('<div align="center" style="width: 100%; height:100%; overflow: auto !important; -webkit-overflow-scrolling: touch !important;">\
      <object id="pdfObject" width="100%" height="1000000000000" align="center" data="content/lessons/12/t.pdf" type="application/pdf" onload="setPDFHeight()">You have no plugin installed</object></div>');  
</script>

분명히 완벽하지는 않지만 (실제로 페이지 높이를 무한대로 확장한다는 점을 감안할 때) 지금까지 찾은 유일한 해결 방법입니다.


내가 시도했을 때 지금까지 완전히 작동하지 않은 솔루션은 없었지만 (때로는 보조로드에서만 버그가 있음) 해결 방법으로 여기에 설명 된대로 개체 요소를 사용한 다음 스크롤 가능한 div로 래핑 한 다음 개체를 매우 높은 높이 (5000px)가 나를 위해 일했습니다. 그것은 큰 해결 방법이며 믿을 수 없을 정도로 잘 작동하지 않습니다 (우선 5000px 이상의 페이지는 문제를 일으킬 수 있습니다-10000px는 나를 위해 완전히 망쳤습니다).하지만 일부 테스트 사례에서 작업을 완료하는 것 같습니다.

var style = 'left: ...px; top: ...px; ' +
        'width: ...px; height: ...px; border: ...';

if (isIOs) {
    style += '; overflow: scroll !important; -webkit-overflow-scrolling: touch !important;';
    html = '<div style="' + style + '">' +
           '<object type="text/html" data="http://example.com" ' +
           'style="width: 100%; height: 5000px;"></object>' +
           '</div>';
}
else {
    style += '; overflow: auto;';
    html = '<iframe src="http://example.com" ' +
           'style="' + style + '"></iframe>';
}

Apple이 Safari iFrame 문제를 해결하기를 바랍니다.


문제

나는 모든 것이 (말 그대로) 여러 수준의 iframe에 중첩되어 있는 크고 복잡하고 지저분한 오래된 사이트를 유지하는 데 도움을줍니다 . 이는 다음과 같은 문제를 야기합니다.

  1. HTML 구조를 변경하면 수년 동안 수정되지 않은 스크립트와 스타일 시트가 손상 될 위험이 있습니다.
  2. 모든 iframe 및 src 문서를 수동으로 찾고 수정하려면 너무 많은 시간과 노력이 필요합니다.

솔루션은 지금까지 게시 된 가운데, 이것이 내가 극복 불행하게도 1. 도전하는 것을 본 적이 단 하나, 일부 iframe을에서 작동하지 않는 것, 때, 스크롤 다른 원인이 보인다 glitchy은 (매우이다 응답하지 않는 링크 및 양식 컨트롤과 같은 페이지의 버그).

해결책

위의 상황이 상황과 비슷하게 들리면 다음 스크립트를 시도해 볼 수 있습니다. 기본 스크롤을 무시하고 대신 모든 iframe을 해당 뷰포트 경계 내에서 드래그 할 수있게 만듭니다. 최상위 iframe을 포함하는 문서에만 추가하면됩니다. 필요에 따라 수정 사항을 그들과 그 자손에게 적용합니다.

다음은 작동하는 바이올린 *이며 코드는 다음과 같습니다.

(function() {
  var mouse = false //Set mouse=true to enable mouse support
    , iOS = /iPad|iPhone|iPod/.test(navigator.platform);
  if(mouse || iOS) {
    (function() {
      var currentFrame
        , startEvent, moveEvent, endEvent
        , screenY, translateY, minY, maxY
        , matrixPrefix, matrixSuffix
        , matrixRegex = /(.*([\.\d-]+, ?){5,13})([\.\d-]+)(.*)/
        , min = Math.min, max = Math.max
        , topWin = window;
      if(!iOS) {
        startEvent = 'mousedown';
        moveEvent = 'mousemove';
        endEvent = 'mouseup';
      }
      else {
        startEvent = 'touchstart';
        moveEvent = 'touchmove';
        endEvent = 'touchend';
      }
      setInterval(scrollFix, 500);
      function scrollFix() {fixSubframes(topWin.frames);}
      function fixSubframes(wins) {for(var i = wins.length; i; addListeners(wins[--i]));}
      function addListeners(win) {
        try {
          var doc = win.document;
          if(!doc.draggableframe) {
            win.addEventListener('unload', resetFrame);
            doc.draggableframe = true;
            doc.addEventListener(startEvent, touchStart);
            doc.addEventListener(moveEvent, touchMove);
            doc.addEventListener(endEvent, touchEnd);
          }
          fixSubframes(win.frames);
        }
        catch(e) {}
      }
      function resetFrame(e) {
        var doc = e.target
          , win = doc.defaultView
          , iframe = win.frameElement
          , style = getComputedStyle(iframe).transform;
        if(iframe===currentFrame) currentFrame = null;
        win.removeEventListener('unload', resetFrame);
        doc.removeEventListener(startEvent, touchStart);
        doc.removeEventListener(moveEvent, touchMove);
        doc.removeEventListener(endEvent, touchEnd);
        if(style !== 'none') {
          style = style.replace(matrixRegex, '$1|$3|$4').split('|');
          iframe.style.transform = style[0] + 0 + style[2];
        }
        else iframe.style.transform = null;
        iframe.style.WebkitClipPath = null;
        iframe.style.clipPath = null;
        delete doc.draggableiframe;
      }
      function touchStart(e) {
        var iframe, style, offset, coords
          , touch = e.touches ? e.touches[0] : e
          , elem = touch.target
          , tag = elem.tagName;
        currentFrame = null;
        if(tag==='TEXTAREA' || tag==='SELECT' || tag==='HTML') return;
        for(;elem.parentElement; elem = elem.parentElement) {
          if(elem.scrollHeight > elem.clientHeight) {
            style = getComputedStyle(elem).overflowY;
            if(style==='auto' || style==='scroll') return;
          }
        }
        elem = elem.ownerDocument.body;
        iframe = elem.ownerDocument.defaultView.frameElement;
        coords = getComputedViewportY(elem.clientHeight < iframe.clientHeight ? elem : iframe);
        if(coords.elemTop >= coords.top && coords.elemBottom <= coords.bottom) return;
        style = getComputedStyle(iframe).transform;
        if(style !== 'none') {
          style = style.replace(matrixRegex, '$1|$3|$4').split('|');
          matrixPrefix = style[0];
          matrixSuffix = style[2];
          offset = parseFloat(style[1]);
        }
        else {
          matrixPrefix = 'matrix(1, 0, 0, 1, 0, ';
          matrixSuffix = ')';
          offset = 0;
        }
        translateY = offset;
        minY = min(0, offset - (coords.elemBottom - coords.bottom));
        maxY = max(0, offset + (coords.top - coords.elemTop));
        screenY = touch.screenY;
        currentFrame = iframe;
      }
      function touchMove(e) {
        var touch, style;
        if(currentFrame) {
          touch = e.touches ? e.touches[0] : e;
          style = min(maxY, max(minY, translateY + (touch.screenY - screenY)));
          if(style===translateY) return;
          e.preventDefault();
          currentFrame.contentWindow.getSelection().removeAllRanges();
          translateY = style;
          currentFrame.style.transform = matrixPrefix + style + matrixSuffix;
          style = 'inset(' + (-style) + 'px 0px ' + style + 'px 0px)';
          currentFrame.style.WebkitClipPath = style;
          currentFrame.style.clipPath = style;
          screenY = touch.screenY;
        }
      }
      function touchEnd() {currentFrame = null;}
      function getComputedViewportY(elem) {
        var style, offset
          , doc = elem.ownerDocument
          , bod = doc.body
          , elemTop = elem.getBoundingClientRect().top + elem.clientTop
          , elemBottom = elem.clientHeight
          , viewportTop = elemTop
          , viewportBottom = elemBottom + elemTop
          , position = getComputedStyle(elem).position;
        try {
          while(true) {
            if(elem === bod || position === 'fixed') {
              if(doc.defaultView.frameElement) {
                elem = doc.defaultView.frameElement;
                position = getComputedStyle(elem).position;
                offset = elem.getBoundingClientRect().top + elem.clientTop;
                viewportTop += offset;
                viewportBottom = min(viewportBottom + offset, elem.clientHeight + offset);
                elemTop += offset;
                doc = elem.ownerDocument;
                bod = doc.body;
                continue;
              }
              else break;
            }
            else {
              if(position === 'absolute') {
                elem = elem.offsetParent;
                style = getComputedStyle(elem);
                position = style.position;
                if(position === 'static') continue;
              }
              else {
                elem = elem.parentElement;
                style = getComputedStyle(elem);
                position = style.position;
              }
              if(style.overflowY !== 'visible') {
                offset = elem.getBoundingClientRect().top + elem.clientTop;
                viewportTop = max(viewportTop, offset);
                viewportBottom = min(viewportBottom, elem.clientHeight + offset);
              }
            }
          }
        }
        catch(e) {}
        return {
          top: max(viewportTop, 0)
          ,bottom: min(viewportBottom, doc.defaultView.innerHeight)
          ,elemTop: elemTop
          ,elemBottom: elemBottom + elemTop
        };
      }
    })();
  }
})();

* jsfiddle에는 테스트 목적으로 마우스 지원이 활성화되어 있습니다. 프로덕션 사이트에서는 mouse = false로 설정해야합니다.


많은 악화 끝에 ipad의 iframe에서 스크롤하는 방법을 발견했습니다. 비결은 iframe 영역의 왼쪽 (그리고 테두리의 약간 바깥 쪽)에서 세로 손가락 스 와이프 (한 손가락은 괜찮음)를 수행하는 것이 었습니다. 노트북이나 PC에서는 스크롤바가 오른쪽에 있으므로 자연스럽게 ipad에서 오른쪽 손가락 동작을 실험하는 데 많은 시간을 보냈습니다. 왼쪽을 시도했을 때만 iframe이 스크롤됩니다.


overflow: auto;스타일에 추가 하면 두 손가락 스크롤이 작동합니다.

참고 URL : https://stackoverflow.com/questions/4599153/iframes-and-the-safari-on-the-ipad-how-can-the-user-scroll-the-content

반응형