모두와 나누는 웹개발 노트

share and care with love.

CSS & HTML & JavaScript

[JS] 유튜브 embed 반응형으로 바꾸기

mere hope 2021. 11. 20. 15:05

유튜브 영상을 embed 하는 경우, 특히 Youtube에서 공유하기로 코드를 복붙하는 경우에는 가로 세로 사이즈가 고정되어 들어가게 된다.

이때 HTML의 상단 </head> 바로 위에 코드를 넣어주자:

<script type="text/javascript">
  $(window).resize(function(){resizeYoutube();});
  $(function(){resizeYoutube();});
  function resizeYoutube(){ $("iframe").each(function(){ if( /^https?:\/\/www.youtube.com\/embed\//g.test($(this).attr("src")) ){ $(this).css("width","100%"); $(this).css("height",Math.ceil( parseInt($(this).css("width")) * 480 / 854 ) + "px");} }); }
</script>

이렇게 하면, 알아서 영상 비율을 유지하면서 너비를 100%로 꽉차게 바꿔준다.

특히 티스토리와 같은 블로그에 써먹기 좋다.
스킨편집 > html편집 화면에서 아래와 같이 </head> 위에 코드를 넣어주면 끝.

 

반응형
LIST