워드프레스에 삽입한 Youtube 영상을 반응형으로 바꿔주기

블로그 스킨을 변경하면 이것저것 테스트 해봐야 하는게 있는데 그 중 하나가 이거임.

이전에 썼던 글중에 유툽 영상 넓이가 본문에 박히니 PC나 태블릿 처럼 가로 넓이가 넓은 뷰에서는 정상으로 보이지만 핸드폰 처럼 좁은데서는 이렇게 화면을 뚫고 나가는 일이 생김..

이전에도 이런거 수정해주는 코드를 올린적이 있는데… (유튜브 프레임 크기 자동 조절되게 하기) 이때 쓰던 스킨은 화면을 삐져나가는것은 알아서 줄여주는 기능이 내장(?) 되어 있어서 작은것만 키우면 됬는데 이번 Twenty Twenty Three 테마는 그게 안되서 검색해보고 몇개 블로그를 참고 해서 하나 작성함. (사실은 jquery로 작성한걸 생짜 javascript로 변환한거 정도)

//유투브 영상 크기 자동 조절해주는 코드 
function youtube_auto_resizer(){
    ?><script type="text/javascript">window.addEventListener('DOMContentLoaded', function(){
    if(typeof YOUTUBE_VIDEO_MARGIN == 'undefined') {
        YOUTUBE_VIDEO_MARGIN=5;
    }
    
    var nodeList =  document.getElementsByTagName('iframe');
    
    for( var index = 0; index < nodeList.length; index++ ){
        var node = nodeList.item(index);
        var attr = node.getAttribute('src');
        
        if ( attr.match(/(https?:)?//www.youtube.com/) ){
            var width = node.getAttribute('width');
            var height = node.getAttribute('height');
            var ar = width/height;
            
            //하단 여백용 계산
            var paddingBottom = height/width*100;
            paddingBottom = paddingBottom.toFixed(2);
            
            //화면 폭이 850 보다 작으면 키운다. 
            if (width < 850) {
                width = 850;
                height = parseInt(width/ar);
            }

            node.style.position = 'absolute';
            node.style.top = 0;
            node.style.left = 0;
            node.style.width = '100%';
            node.style.height = '100%';
            node.style.maxWidth = width+'px';
            node.style.maxHeight = height+'px';
            
            var tmp = document.createElement('div');
            tmp.innerHTML = node.outerHTML;
            tmp.style.maxWidth = width+'px';
            tmp.style.margin = '0 auto';
            tmp.style.padding = YOUTUBE_VIDEO_MARGIN+'px';
            
            var tmp2 = document.createElement('div');
            tmp2.innerHTML = tmp.outerHTML;
            tmp2.style.position = 'relative';
            tmp2.style.paddingBottom = paddingBottom+'%';
            tmp2.style.height = 0;
            tmp2.style.overflow = 'hidden';
            
            node.parentNode.insertBefore(tmp2, node);
            node.remove();
        }
    }
});</script><?php
}
add_action('wp_footer', 'youtube_auto_resizer');

내 블로그 화면폭이 850이라 그보다 작으면 늘리는거 정도 추가했음. 코드는 차일드 테마 functions.php 에 넣으면 됩니다.

유투브 기본 퍼오기 코드로 해도 화면 폭에 맞춰서 잘 조절되는걸 확인함.

참고 사이트 : https://www.skipser.com/p/2/p/auto-resize-youtube-videos-in-responsive-layout.html, http://triki.net/prgm/1491


Comments

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다