2017-05-22 3 views
1

그래서 기본적으로 봤지만이를 수행하는 방법에 대한 연구를 수행했지만 작동하도록 관리하지는 못했습니다. width라는 변수를 선언했습니다. 내 JS가 화면의 너비가 660px보다 작 으면 너비는 140px가되어야하며 그렇지 않으면 100px가되어야합니다. 변수 "width"는 장치 "phone"을 돌릴 때만 변경해야하지만 작동하지 않습니다. 변수를 장치 회전 시마다 화면 너비를 확인해야합니다. 나는 오랫동안 그것을 해왔지만 해결할 수 없었다. 나는 미디어 쿼리를 알고,하지만 난 다른 이유로 JS에 변수를 변경하려면 .. 이벤트가 그래서 당신의 코드가 될 것입니다 deviceorientation라고회전시 변수의 값 변경 Js

var width = 0; 
    function check() 
    { 

if (window.innerWidth < 660) 
    { 
    width = 140; 
    } 
    else{ 
    width = 100; 
    } 
} 


window.addEventListener("orientationEvent", check); 
document.write(width); 

답변

1

위해서 orientationchange이 window.matchMediaMediaQueryList 들여다 나열해야합니다.

하지만 최신 기능이며 모든 브라우저에서 지원되지 않을 수 있습니다.

var mediaQueryList = window.matchMedia("(orientation: portrait)"); 
// Create the query list. 
function handleOrientationChange(mql) { ... } 
// Define a callback function for the event listener. 
mediaQueryList.addListener(handleOrientationChange); 
// Add the callback function as a listener to the query list. 

handleOrientationChange(); // Run the orientation change handler once. 

function handleOrientationChange(evt) { 
    if (evt.matches) { 
    /* The viewport is currently in portrait orientation */ 
    } else { 
    /* The viewport is currently in landscape orientation */ 
    } 
} 

다음은 뷰포트가 변경 될 때 changeWidth 메서드를 호출하는 것입니다.

var width = 0; 
function changeWidth() { 

    if (window.matchMedia("(min-width: 600px)").matches) { 
     /* the viewport is at least 600 pixels wide */ 
     width = 140; 
    } else { 
     /* the viewport is less than 600 pixels wide */ 
     width = 100; 
    } 

} 

자세한 문서 관련 정보 here.

+0

if 및 else의 handleOrientationChange (evt)에서 changeWidth() 함수를 호출해야합니까? –

+0

이상적입니다. 그러나 오리엔테이션에 상관없이 호출하고 싶다면 else를 제거하고 거기에서'changeWidth' 메소드를 호출하십시오. 위의 코드는 현재 방향이'portrait' 모드로 가정하고 오리엔테이션이 변경되면'handleOrientationChange' 메소드가 호출됩니다. – WitVault

+0

작동하지 않습니다. changeWidth(); handleOrientationChange (evt) {}에서 if 및 else 대신에 작동하지만 .../ –

1

JS에게 :

window.addEventListener('deviceorientation', check); 

자바 스크립트의 이벤트는 모두 소문자임을 기억하십시오.

1

사실 당신은 내가 당신을 제안 MDN

var width = 0; 
 

 
function check(){ 
 
    if (window.innerWidth < 660) { 
 
    width = 140; 
 
    } else { 
 
    width = 100; 
 
    } 
 
    
 
    // Just for demo 
 
    document.querySelector('body').innerHTML = width; 
 
} 
 

 

 
window.addEventListener("orientationchange", check);