私はモバイル機器専用のウェブサイトを構築しています。特に横長モードで表示されるのが1ページあります。
そのページにアクセスしているユーザーがポートレートモードで表示しているかどうかを検出し、表示されている場合は、そのページがランドスケープモードで最もよく表示されていることを知らせるメッセージを表示する方法はありますか。ユーザーがすでに横長モードで表示している場合は、メッセージは表示されません。
そのため、基本的には、サイトがビューポートの向きを縦の場合は検出し、次にこのページは横モードで表示するのが最も良いという警告メッセージを表示します。
どうもありがとう、ダン
if(window.innerHeight > window.innerWidth){
alert("Please use Landscape!");
}
jQuery Mobileには、このプロパティの変更を処理するイベントがあります。後で誰かがローテーションした場合に警告したい場合は - orientationchange
また、いくつかのグーグルの後、window.orientation
をチェックしてください(これは度で測られると思います...)
window.matchMedia
を使用することもできます。これはCSS構文によく似ているので、私はこれを使用します。
if (window.matchMedia("(orientation: portrait)").matches) {
// you're in PORTRAIT mode
}
if (window.matchMedia("(orientation: landscape)").matches) {
// you're in LANDSCAPE mode
}
IPad 2でテストしました。
デビッドウォルシュはより良いとポイントにアプローチしています。
// Listen for orientation changes
window.addEventListener("orientationchange", function() {
// Announce the new orientation number
alert(window.orientation);
}, false);
これらの変更中に、window.orientationプロパティが変わる可能性があります。値0はポートレートビューを意味し、-90はデバイスが右にランドスケープ回転されることを意味し、90はデバイスが左にランドスケープ回転されることを意味します。
あなたはCSS3を使うことができます:
@media screen and (orientation:landscape)
{
body
{
background: red;
}
}
その方法はいくつかあります。例えば:
window.orientation
値を確認してくださいinnerHeight
とinnerWidth
の比較以下の方法のいずれかを適用することができます。
デバイスがポートレートモードになっているか確認してください
function isPortrait() {
return window.innerHeight > window.innerWidth;
}
デバイスが横長モードになっているか確認してください
function isLandscape() {
return (window.orientation === 90 || window.orientation === -90);
}
使用例
if (isPortrait()) {
alert("This page is best viewed in landscape mode");
}
方位の変化をどうやって検出するのですか?
$(document).ready(function() {
$(window).on('orientationchange', function(event) {
console.log(orientation);
});
});
デスクトップコンピュータでブラウザウィンドウのサイズを変更する場合は、横長または縦長の両方になる可能性があるため、ウィンドウの代わりにscreenを使用することがより安定した解決策だと思います。
if (screen.height > screen.width){
alert("Please use Landscape!");
}
私の毎日のコーディングにこれらのすばらしいコメントをすべて適用するために、私のすべてのアプリケーション間の継続性のために、私はjqueryとjqueryモバイルコードの両方で以下を使用することにしました。
window.onresize = function (event) {
applyOrientation();
}
function applyOrientation() {
if (window.innerHeight > window.innerWidth) {
alert("You are now in portrait");
} else {
alert("You are now in landscape");
}
}
固定されたwindow.orientationクエリを試してはいけません(0、90などはポートレート、ランドスケープなどを意味するわけではありません):
http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation/
IOS 7でも、ブラウザへのアクセス方法によっては、常に縦向きになるとは限りません。
いくつかの実験の後、私はオリエンテーション対応デバイスを回転させることは常にブラウザウィンドウのresize
イベントを引き起こすことを発見しました。だからあなたのリサイズハンドラで次のような関数を呼び出すだけです:
function is_landscape() {
return (window.innerWidth > window.innerHeight);
}
私は2つの解決策を組み合わせました、そしてそれは私のためにうまく働きます。
window.addEventListener("orientationchange", function() {
if (window.matchMedia("(orientation: portrait)").matches) {
alert("PORTRAIT")
}
if (window.matchMedia("(orientation: landscape)").matches) {
alert("LANSCAPE")
}
}, false);
次の方法でオリエンテーションを取得します(jsコード内でいつでも)。
window.orientation
window.orientation
が0
または180
を返すときは縦モードになり、90
または270
を返すときは横モードになります。
私は最も投票された答えに反対します。 screen
ではなくwindow
を使用
if(screen.innerHeight > screen.innerWidth){
alert("Please use Landscape!");
}
それを行うための適切な方法です。 window.height
で計算すると、Android上で問題が発生します。キーボードが開いていると、ウィンドウは縮小されます。だからwindowの代わりにscreenを使ってください。
screen.orientation.type
は良い答えですがIEの場合です。 https://caniuse.com/#search=screen.orientation
幅/高さの比較に基づいて方向を決定するもう1つの方法
var mql = window.matchMedia("(min-aspect-ratio: 4/3)");
if (mql.matches) {
orientation = 'landscape';
}
あなたは "サイズ変更"イベントでそれを使用します:
window.addEventListener("resize", function() { ... });
向きが変わってもiOSはscreen.width
とscreen.height
を更新しません。 Androidはwindow.orientation
が変更されても更新しません。
この問題に対する私の解決策:
var isAndroid = /(Android)/i.test(navigator.userAgent);
if(isAndroid)
{
if(screen.width < screen.height){
//portrait mode on Android
}
} else {
if(window.orientation == 0){
//portrait mode iOS and other devices
}
}
次のコードを使用して、AndroidとiOSの両方でこの方向の変化を検出できます。
var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
window.addEventListener(orientationEvent, function() {
alert("the orientation has changed");
}, false);
onorientationchange
イベントがサポートされていない場合、バインドされるイベントはresize
イベントになります。
//see also http://stackoverflow.com/questions/641857/javascript-window-resize-event
//see also http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html
/*
Be wary of this:
While you can just hook up to the standard window resize event, you'll find that in IE, the event is fired once for every X and once for every Y axis movement, resulting in a ton of events being fired which might have a performance impact on your site if rendering is an intensive task.
*/
//setup
window.onresize = function(event) {
window_resize(event);
}
//timeout wrapper points with doResizeCode as callback
function window_resize(e) {
window.clearTimeout(resizeTimeoutId);
resizeTimeoutId = window.setTimeout('doResizeCode();', 10);
}
//wrapper for height/width check
function doResizeCode() {
if(window.innerHeight > window.innerWidth){
alert("Please view in landscape");
}
}
$(window).on("orientationchange",function( event ){
alert(screen.orientation.type)
});
CCSのみ
@media (max-width: 1024px) and (orientation: portrait){ /* tablet and smaller */
body:after{
position: absolute;
z-index: 9999;
width: 100%;
top: 0;
bottom: 0;
content: "";
background: #212121 url(http://i.stack.imgur.com/sValK.png) 0 0 no-repeat; /* replace with an image that tells the visitor to rotate the device to landscape mode */
background-size: 100% auto;
opacity: 0.95;
}
}
場合によっては、訪問者がデバイスを回転させた後にページにリロードするための小さなコードを追加して、CSSが正しくレンダリングされるようにすることができます。
window.onorientationchange = function() {
var orientation = window.orientation;
switch(orientation) {
case 0:
case 90:
case -90: window.location.reload();
break; }
};
270ではなく、-90(マイナス90)にすることもできます。
道を導くためのtobyodaviesに感謝します。
モバイルデバイスの向きに基づいて警告メッセージを表示するには、function setHeight() {
内に次のスクリプトを実装する必要があります。
if(window.innerHeight > window.innerWidth){
alert("Please view in landscape");
}
これは以前の答えを拡張したものです。私が見つけた最善の解決策は、CSS3メディアクエリが満たされた場合にのみ表示される無害なCSS属性を作成し、その属性に対するJSテストを行うことです。
たとえば、CSSでは次のようになります。
@media screen only and (orientation:landscape)
{
// Some innocuous rule here
body
{
background-color: #fffffe;
}
}
@media screen only and (orientation:portrait)
{
// Some innocuous rule here
body
{
background-color: #fffeff;
}
}
それからJavaScriptに行きます(私は楽しみのためにjQueryを使っています)。色の宣言は奇妙かもしれないので、他のものを使用したいと思うかもしれませんが、これは私がそれをテストするために見つけた最も確実な方法です。その後、サイズ変更イベントを使用して切り替えをピックアップできます。全部まとめると:
function detectOrientation(){
// Referencing the CSS rules here.
// Change your attributes and values to match what you have set up.
var bodyColor = $("body").css("background-color");
if (bodyColor == "#fffffe") {
return "landscape";
} else
if (bodyColor == "#fffeff") {
return "portrait";
}
}
$(document).ready(function(){
var orientation = detectOrientation();
alert("Your orientation is " + orientation + "!");
$(document).resize(function(){
orientation = detectOrientation();
alert("Your orientation is " + orientation + "!");
});
});
これの最も良い部分は、私がこの答えを書いている時点では、デスクトップインターフェースには何の影響も与えないように見えるということです。なぜならそれらは(一般的に)ページへの方向付けのための引数を渡さないからです。
IOSデバイス上のJavaScriptのウィンドウオブジェクトには、デバイスの回転を決定するために使用できるorientationプロパティがあります。以下は、さまざまな向きのiOSデバイス(iPhone、iPad、iPodなど)のwindow.orientationの値を示しています。
この解決策は、Androidデバイスにも機能します。私は、Androidのネイティブブラウザ(インターネットブラウザ)とChromeブラウザをチェックしました。古いバージョンでもチェックしました。
function readDeviceOrientation() {
if (Math.abs(window.orientation) === 90) {
// Landscape
} else {
// Portrait
}
}
David Walshの記事( モバイルデバイスの向きの変化を検出 )に基づいて、私が見つけた最良の方法は次のとおりです。
if ( window.matchMedia("(orientation: portrait)").matches ) {
alert("Please use Landscape!")
}
説明:
Window.matchMedia() は、メディアクエリルールを定義し、いつでもその妥当性をチェックすることを可能にするネイティブメソッドです。
このメソッドの戻り値にonchange
リスナーを添付すると便利です。例:
var mediaQueryRule = window.matchMedia("(orientation: portrait)")
mediaQueryRule.onchange = function(){ alert("screen orientation changed") }
私はAndroid Chromeで使っています "The Screen Orientation API"
現在の向きを調べるには、console.log(screen.orientation.type)(そしておそらくscreen.orientation.angle)を呼び出します。
結果:portrait-primary |ポートレート - セカンダリ|ランドスケーププライマリランドスケープセカンダリ
以下は私のコードです、私はそれが役に立つことを願っています:
var m_isOrientation = ("orientation" in screen) && (typeof screen.orientation.lock == 'function') && (typeof screen.orientation.unlock == 'function');
...
if (!isFullscreen()) return;
screen.orientation.lock('landscape-secondary').then(
function() {
console.log('new orientation is landscape-secondary');
},
function(e) {
console.error(e);
}
);//here's Promise
...
screen.orientation.unlock();
これが私が使っているものです。
function getOrientation() {
// if window.orientation is available...
if( window.orientation && typeof window.orientation === 'number' ) {
// ... and if the absolute value of orientation is 90...
if( Math.abs( window.orientation ) == 90 ) {
// ... then it's landscape
return 'landscape';
} else {
// ... otherwise it's portrait
return 'portrait';
}
} else {
return false; // window.orientation not available
}
}
実装
window.addEventListener("orientationchange", function() {
// if orientation is landscape...
if( getOrientation() === 'landscape' ) {
// ...do your thing
}
}, false);
screen.orientation.addEventListener("change", function(e) {
console.log(screen.orientation.type + " " + screen.orientation.angle);
}, false);
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotation Test</title>
<link type="text/css" href="css/style.css" rel="stylesheet"></style>
<script src="js/jquery-1.5.min.js" type="text/javascript"></script>
<script type="text/javascript">
window.addEventListener("resize", function() {
// Get screen size (inner/outerWidth, inner/outerHeight)
var height = $(window).height();
var width = $(window).width();
if(width>height) {
// Landscape
$("#mode").text("LANDSCAPE");
} else {
// Portrait
$("#mode").text("PORTRAIT");
}
}, false);
</script>
</head>
<body onorientationchange="updateOrientation();">
<div id="mode">LANDSCAPE</div>
</body>
</html>
一部のデバイスはorientationchange
イベントを提供しませんが、ウィンドウのサイズ変更イベントを発生させます。
// Listen for resize changes
window.addEventListener("resize", function() {
// Get screen size (inner/outerWidth, inner/outerHeight)
}, false);
Orientationchangeイベントよりも少しわかりにくいですが、非常にうまく機能します。 こちらをチェックしてください
window.orientation
に関して注意すべきことの一つは、あなたがモバイルデバイス上にいない場合はundefined
を返すということです。そのため、向きをチェックするための適切な関数は次のようになります。ここで、x
はwindow.orientation
です。
//check for orientation
function getOrientation(x){
if (x===undefined){
return 'desktop'
} else {
var y;
x < 0 ? y = 'landscape' : y = 'portrait';
return y;
}
}
そのようにそれを呼ぶ:
var o = getOrientation(window.orientation);
window.addEventListener("orientationchange", function() {
o = getOrientation(window.orientation);
console.log(o);
}, false);
それともあなたはこれを使用することができます..
window.addEventListener("orientationchange", function() {
if (window.orientation == "90" || window.orientation == "-90") {
//Do stuff
}
}, false);
screen.orientation
を使用してユーザーが自分のデバイスをポートレートモードに切り替えたかどうかを検出できる方法があります。
以下のコードを使用してください。
screen.orientation.onchange = function () {
var type = screen.orientation.type;
if (type.match(/portrait/)) {
alert('Please flip to landscape, to use this app!');
}
}
これで、onchange
は、ユーザーがデバイスをフリップしたときに起動され、ユーザーがポートレートモードを使用しているときにアラートがポップアップするようになりました。
あなたが最新のブラウザを持っているならwindow.orientation
は動かないかもしれません。その場合、角度を取得するために次のコードを使用します -
var orientation = window.screen.orientation.angle;
これはまだ実験的な技術です、あなたはブラウザの互換性をチェックすることができます ここ