뷰포트 방향 감지(방향이 세로 방향인 경우) 사용자에게 지침을 알리는 경보 메시지 표시
모바일 전용 웹사이트를 만들고 있습니다.가로 모드에서 가장 잘 보이는 페이지가 있습니다.
페이지를 방문한 사용자가 세로 모드로 페이지를 보고 있는지 여부를 감지하고, 만약 그렇다면 페이지가 가로 모드로 가장 잘 표시됨을 사용자에게 알리는 메시지를 표시할 수 있는 방법이 있습니까?사용자가 이미 가로 모드로 표시하고 있는 경우는, 메세지는 표시되지 않습니다.
따라서 기본적으로 뷰포트 방향을 검출하고 방향이 세로일 경우 사용자에게 이 페이지가 가로 모드에서 가장 잘 표시됨을 알리는 경보 메시지를 표시합니다.
if(window.innerHeight > window.innerWidth){
alert("Please use Landscape!");
}
jQuery Mobile에 이 속성 변경을 처리하는 이벤트가 있습니다...누군가 나중에 회전할 때 경고하고 싶은 경우 -
구글 후에, 「CHANGE」를해 주세요.window.orientation한 것 ...)
편집: 모바일 디바이스에서 키보드를 열면 위의 오류가 발생할 수 있으므로screen.availHeight ★★★★★★★★★★★★★★★★★」screen.availWidth키보드를 연 후에도 적절한 높이와 폭을 제공합니다.
if(screen.availHeight > screen.availWidth){
alert("Please use Landscape!");
}
이 경우에도 하실 수 있습니다.window.matchMediaCSS 구문과 매우 유사하기 때문에 사용하고 있습니다.
if (window.matchMedia("(orientation: portrait)").matches) {
// you're in PORTRAIT mode
}
if (window.matchMedia("(orientation: landscape)").matches) {
// you're in LANDSCAPE mode
}
iPad 2에서 테스트 완료.
David Walsh는 더 낫고 정확한 접근법을 가지고 있다.
// Listen for orientation changes
window.addEventListener("orientationchange", function() {
// Announce the new orientation number
alert(window.orientation);
}, false);
이러한 변경 중에 window.orientation 속성이 변경될 수 있습니다.값이 0이면 세로 표시, -90이면 디바이스가 오른쪽으로 회전하고 있다는 의미, 90이면 디바이스가 왼쪽으로 회전하고 있다는 의미입니다.
http://davidwalsh.name/orientation-change
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);
});
});
데스크톱 컴퓨터에서 브라우저 창의 크기를 조정할 경우 가로 또는 세로 둘 다일 수 있기 때문에 창 대신 화면을 사용하는 것이 더 안정적인 해결책이라고 생각합니다.
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");
}
}
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; }
};
고정된 창을 사용하지 마십시오.방향 질문(0, 90 등은 세로, 가로 등을 의미하지 않습니다).
http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation/
iOS7에서도 브라우저 0에 어떻게 접속하느냐에 따라 세로 방향은 다릅니다.
나는 가장 많이 투표된 답변에 동의하지 않는다.사용하다screen가 아니라window
if(screen.innerHeight > screen.innerWidth){
alert("Please use Landscape!");
}
그게 올바른 방법이야.로 계산하면window.heightAndroid에서는 문제가 발생합니다.키보드가 열려 있으면 창이 축소됩니다.그래서 창문 대신 화면을 사용하세요.
그screen.orientation.type좋은 답변이지만 IE를 사용합니다.https://caniuse.com/ #search=screen.orientation
$(window).on("orientationchange",function( event ){
alert(screen.orientation.type)
});
몇 가지 실험 후 방향 인식 장치를 회전하면 항상 브라우저 창의 작동이 트리거된다는 것을 발견했습니다.resize따라서 크기 조정 핸들러에서 다음과 같은 함수를 호출할 수 있습니다.
function is_landscape() {
return (window.innerWidth > window.innerHeight);
}
저는 두 가지 솔루션을 결합했고, 제게는 잘 작동합니다.
window.addEventListener("orientationchange", function() {
if (window.matchMedia("(orientation: portrait)").matches) {
alert("PORTRAIT")
}
if (window.matchMedia("(orientation: landscape)").matches) {
alert("LANSCAPE")
}
}, false);
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이벤트입니다.
(js 코드로 언제든지) 다음 방법으로 오리엔테이션을 받을 수 있습니다.
window.orientation
언제window.orientation돌아온다0또는180세로 모드가 되어 있을 때, 돌아올 때90또는270가로 모드가 됩니다.
최신 브라우저가 있는 경우window.orientation동작하지 않을 수 있습니다.이 경우 각도를 얻기 위해 다음 코드를 사용합니다.
var orientation = window.screen.orientation.angle;
이것은 아직 시험적인 기술입니다.브라우저의 호환성은 이쪽에서 확인할 수 있습니다.
//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");
}
}
너비/높이 비교를 기반으로 방향을 결정하는 또 다른 대안:
var mql = window.matchMedia("(min-aspect-ratio: 4/3)");
if (mql.matches) {
orientation = 'landscape';
}
크기 조정 이벤트에 사용합니다.
window.addEventListener("resize", function() { ... });
다음은 David Walsh의 기사(모바일 디바이스의 오리엔테이션 변경 검출)에 근거한 최선의 방법입니다.
if ( window.matchMedia("(orientation: portrait)").matches ) {
alert("Please use Landscape!")
}
설명:
Window.match Media()는 미디어 쿼리 규칙을 정의하고 언제든지 유효성을 확인할 수 있는 네이티브 메서드입니다.
를 첨부하는 것이 편리하다고 생각합니다.onchange이 메서드의 반환값을 리스너로 설정합니다.예:
var mediaQueryRule = window.matchMedia("(orientation: portrait)")
mediaQueryRule.onchange = function(){ alert("screen orientation changed") }
사용자가 단말기를 세로 모드로 전환했는지 감지할 수 있는 방법이 있습니다.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사용자가 단말기를 뒤집을 때마다 부팅되며 사용자가 세로 모드를 사용할 때 경고가 팝업됩니다.
길을 안내해주신 토비오다비들 덕분입니다.
디바이스의 를 구현해야 .function setHeight() {
if(window.innerHeight > window.innerWidth){
alert("Please view in landscape");
}
270 대신 -90(-90)이 될 수 있습니다.
이것은 앞의 답변으로 확대됩니다.제가 찾은 최고의 솔루션은 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를 funsies로 사용하고 있습니다).색채 선언이 이상할 수 있기 때문에 다른 것을 사용하는 것이 좋을지도 모르지만, 이것은 제가 지금까지 발견한 테스트 방법 중 가장 실수하기 쉬운 방법입니다.그런 다음 크기 조정 이벤트를 사용하여 전환 시 선택할 수 있습니다.모든 것을 정리하면 다음과 같은 이점이 있습니다.
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 + "!");
});
});
이 답변의 가장 좋은 점은 이 답변이 데스크톱 인터페이스에는 아무런 영향을 미치지 않는다는 것입니다. 왜냐하면 데스크톱 인터페이스에서는 (일반적으로) 오리엔테이션에 대한 어떠한 인수도 페이지에 전달하지 않는 것 같기 때문입니다.
Android Chrome "The Screen Orientation API"에 사용하였습니다.
현재 방향을 확인하려면 console.log(screen.orientation.type)를 호출합니다(screen.orientation.angle도 호출할 수 있습니다).
결과: 세로 프라이머리 | 세로 세컨더리 | 가로 프라이머리 | 가로 세컨더리
아래가 제 코드입니다. 도움이 되었으면 합니다.
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();
- Android Chrome에서만 테스트 - OK
screen.orientation.addEventListener("change", function(e) {
console.log(screen.orientation.type + " " + screen.orientation.angle);
}, false);
iOS 디바이스에서 JavaScript의 창 개체에는 디바이스 회전을 결정하는 데 사용할 수 있는 방향 속성이 있습니다.다음은 다양한 방향의 iOS 기기(예: iPhone, iPad, iPod)에 대한 가치 창.방향입니다.
이 솔루션은 안드로이드 기기에서도 작동합니다.안드로이드 네이티브 브라우저(인터넷 브라우저)와 크롬 브라우저에서도 이전 버전에서도 확인했습니다.
function readDeviceOrientation() {
if (Math.abs(window.orientation) === 90) {
// Landscape
} else {
// Portrait
}
}
이게 제가 쓰는 거예요.
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);
은 '비밀번호가 없다'를 제공하지 않습니다.orientationchange이벤트, 단 창의 크기 조정 이벤트를 발생시킵니다.
// Listen for resize changes
window.addEventListener("resize", function() {
// Get screen size (inner/outerWidth, inner/outerHeight)
}, 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>
about한 one one one one one one one one one one one window.orientation 것이다undefined모바일 디바이스가 아닌 경우. 방향을 되어 수 .xwindow.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);
언급URL : https://stackoverflow.com/questions/4917664/detect-viewport-orientation-if-orientation-is-portrait-display-alert-message-ad
'programing' 카테고리의 다른 글
| ALTER TABLE 문에 'ON DELETE CASCADE'를 추가하는 방법 (0) | 2023.03.15 |
|---|---|
| AngularJS 페이지 내 여러 ng-app (0) | 2023.03.15 |
| 후크 사용 시 React batch state update가 기능합니까? (0) | 2023.03.15 |
| C# 어나니머스 타입을 JSON 문자열로 시리얼화하려면 어떻게 해야 하나요? (0) | 2023.03.15 |
| 스프링 데이터 jpa에서 투영 및 사양을 사용하는 방법 (0) | 2023.03.15 |