2017-05-22 6 views
1

基本的に私はグーグルでこれを行う方法を研究しましたが、それを動作させることはできませんでした..私はwidthという変数を宣言しました。画面の幅が660pxより小さい場合は幅を140px、そうでなければ100pxにする必要があります。変数「width」は、デバイス「phone」を回転させているときに変更する必要がありますが、機能しません。私は変数が、デバイスを回転させるたびに画面の幅をチェックする必要があります。私はそれを長い間働いてきましたが、解決できませんでした。回転時の変数の値を変更するJs

window.addEventListener('deviceorientation', check); 
:ので、あなたのコードがされるイベントが deviceorientationと呼ばれ
var width = 0; 
    function check() 
    { 

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


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

答えて

1

をリストする必要があります。

ただし、これは最新の実験的機能であり、すべてのブラウザでサポートされているわけではないことに注意してください。

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'メソッドを呼び出します。上記のコードでは、現在の方向が 'ポートレート'モードであると仮定し、方向が変更されると 'handleOrientationChange'メソッドが呼び出されます。 – WitVault

+0

それは動作していません、私は入れたchangeWidth(); ifおよびelseの代わりにhandleOrientationChange(evt){}、それは働いていません.../ –

1

JS

..私はメディアクエリを知っているが、私は他の理由JSでの変数を変更したいです

JavaScriptのイベントはすべて小文字であることを忘れないでください。

1

実は私はwindow.matchMediaMediaQueryListに見て、あなたをお勧めしますorientationchange 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);

関連する問題