창크기에 따라 불러오는 파일을 다르게 하고 싶은데 방법을 잘모르겠어요
반응형 홈페이지를 제작중입니다.
제작중 열린 페이지의 크기에 따라 연결된 파일이 열렸으면 합니다.
예를 들면 index.php 파일 안에서
창크기가 768px보다 크면
include_once('/pc.php') 가 불러와지고고
창크기가 768보다 작으면
include_once('/mobile.php') 가 불러와지는 방식을 사용하려고 하는데
도저히 어떻게 해야할지 아무리 해봐도 방법을 못찾겠네요
혹시 방법이 있으시면 도움 부탁 드립니다.
답변 5개
$(document).ready(function() {
var windowWidth = $(window).width();
if (windowWidth >= 768) {
$("#content").load("/pc.php");
} else {
$("#content").load("/mobile.php");
}
$(window).on('resize', function() {
location.reload();
});
});
댓글을 작성하려면 로그인이 필요합니다.
내용이 많지 않다면 다음처럼 해도 됩니다
<style>
#w768_2{display:none;}
@media (max-width: 768px) {
#w768_1{display:none;}
#w768_2{display:block;}
}
<style>
<div id='w768_1'><?php include_once('/pc.php');?></div>
<div id='w768_2'><?php include_once('/mobile.php');?></div>
댓글을 작성하려면 로그인이 필요합니다.
여기 내용 참조해서 ajax 로 창크기를 넘기고,
받은 페이지에서 width 에 따라서 include 를 한 후에
해당 페이지의 html 전체 값을 넘겨 받아서,
해당 div에 출력하는 방법이 있습니다.
댓글을 작성하려면 로그인이 필요합니다.
여러가지 방법이 있겠지만 아래의 내용도 한번 참고를 해보세요..
1.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>반응형 페이지</title>
<style>
#content {
width: 100%;
height: 100vh;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div id="content"></div>
<script>
function loadContent() {
var xhr = new XMLHttpRequest();
var url = window.innerWidth > 768 ? 'pc.php' : 'mobile.php';
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('content').innerHTML = xhr.responseText;
}
};
xhr.send();
}
window.onload = loadContent;
window.onresize = loadContent;
</script>
</body>
</html>
2.
index.php
<div id="content"></div>
<script>
// 창크기를 감지하는 함수
function getWindowSize() {
return {
width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
};
}
// 창크기에 따라 적절한 파일을 불러오는 함수
function loadFile() {
var windowSize = getWindowSize();
if (windowSize.width >= 768) {
// 768px 이상이면 pc.php 파일 불러오기
document.getElementById('content').innerHTML = '<?php include_once("/pc.php"); ?>';
} else {
// 768px 미만이면 mobile.php 파일 불러오기
document.getElementById('content').innerHTML = '<?php include_once("/mobile.php"); ?>';
}
}
// 페이지 로드 시 파일 불러오기
window.onload = loadFile;
// 창크기 변경 시 파일 다시 불러오기
window.onresize = loadFile;
</script>
댓글을 작성하려면 로그인이 필요합니다.
일반적인 방법으로는 불가능합니다.
php 자체가 전체 랜더링이기 때문에 반응형 때 불러올 수 없습니다.
하지만, 아예 방법이 없는건 아닙니다만, 좀 손봐야겠지만
jquery 이벤트 중 resize 함수를 이용해,
특정 수치 보다 작거나 같다면 모바일 파일을 ajax 로 로딩해 해당 파일의 내용을 뿌려주면 가능합니다
물론 else 문에서 pc버전 (반대로도 가능합니다.)
"일반적인 방법 자체로는 불가능한게 맞습니다."
댓글을 작성하려면 로그인이 필요합니다.
답변을 작성하려면 로그인이 필요합니다.
로그인