使用事件侦听器检测 window 高度和宽度的变化
Detect change in window height and width with event listener
基本上,我正在与 table 不同方向的人玩配对游戏。如果浏览器调整为横向或移动设备转动,我将其设置为水平 table。如果纵向,则垂直 table。我有点需要一个事件侦听器来检测是纵向还是横向。
给定 2 个问题,可以一起解决或使用单独的代码。
问题 1
我正在桌面上查看我的页面,我调整了 window 的大小,使宽度 = 768 像素和高度 = 767 像素,然后激活横向模式。
是否有一个事件侦听器 仅通过
来确定是否应该显示页面的纵向或横向版本
if(window.innerHeight > window.innerWidth) {
portrait = true;
/*display to portrait version of page*/
}
else {
portrait = false;
/*display to landscape version of page*/
}
或者我是否必须创建一个自定义事件侦听器,在这种情况下如何?
问题2
我正在移动设备上查看我的页面。当它通过转动检测到它处于横向模式时,激活横向模式。
我相信这可以通过
解决
window.addEventListener("orientationchange", function() {
/*display landscape/portrait version*/
}, false);
根据您在确定用户是否处于横向模式后实际尝试执行的操作,有几种不同的实现方式:
检测用户是横向还是纵向
function readDeviceOrientation() {
if (Math.abs(window.orientation) === 90) {
// Landscape
} else {
// Portrait
}
}
使用方向媒体查询调整样式
/* For portrait, we want the tool bar on top */
@media screen and (orientation: portrait) {
#toolbar {
width: 100%;
}
}
/* For landscape, we want the tool bar stick on the left */
@media screen and (orientation: landscape) {
#toolbar {
position: fixed;
width: 2.65em;
height: 100%;
}
p {
margin-left: 2em;
}
li + li {
margin-top: .5em;
}
}
利用jQuery
$( window ).resize(function() {
if (Math.abs(window.orientation) === 90) {
// Do Landscape
} else {
// Do Portrait
}
};
监听方向变化
screen.addEventListener("orientationchange", function () {
console.log("The orientation of the screen is: " + screen.orientation);
});
基本上,我正在与 table 不同方向的人玩配对游戏。如果浏览器调整为横向或移动设备转动,我将其设置为水平 table。如果纵向,则垂直 table。我有点需要一个事件侦听器来检测是纵向还是横向。
给定 2 个问题,可以一起解决或使用单独的代码。
问题 1
我正在桌面上查看我的页面,我调整了 window 的大小,使宽度 = 768 像素和高度 = 767 像素,然后激活横向模式。
是否有一个事件侦听器 仅通过
来确定是否应该显示页面的纵向或横向版本if(window.innerHeight > window.innerWidth) {
portrait = true;
/*display to portrait version of page*/
}
else {
portrait = false;
/*display to landscape version of page*/
}
或者我是否必须创建一个自定义事件侦听器,在这种情况下如何?
问题2
我正在移动设备上查看我的页面。当它通过转动检测到它处于横向模式时,激活横向模式。
我相信这可以通过
解决window.addEventListener("orientationchange", function() {
/*display landscape/portrait version*/
}, false);
根据您在确定用户是否处于横向模式后实际尝试执行的操作,有几种不同的实现方式:
检测用户是横向还是纵向
function readDeviceOrientation() {
if (Math.abs(window.orientation) === 90) {
// Landscape
} else {
// Portrait
}
}
使用方向媒体查询调整样式
/* For portrait, we want the tool bar on top */
@media screen and (orientation: portrait) {
#toolbar {
width: 100%;
}
}
/* For landscape, we want the tool bar stick on the left */
@media screen and (orientation: landscape) {
#toolbar {
position: fixed;
width: 2.65em;
height: 100%;
}
p {
margin-left: 2em;
}
li + li {
margin-top: .5em;
}
}
利用jQuery
$( window ).resize(function() {
if (Math.abs(window.orientation) === 90) {
// Do Landscape
} else {
// Do Portrait
}
};
监听方向变化
screen.addEventListener("orientationchange", function () {
console.log("The orientation of the screen is: " + screen.orientation);
});