在JavaScript中,我可以使用window.screen.height
获取屏幕的高度。现在,如果我有双显示器,并且两个显示器的大小不同,并且我将浏览器窗口从一个显示器移动到另一个显示器,除了定时轮询窗口大小之外,是否有其他方法可以检测到这一点?
在JavaScript中,我可以使用window.screen.height
获取屏幕的高度。现在,如果我有双显示器,并且两个显示器的大小不同,并且我将浏览器窗口从一个显示器移动到另一个显示器,除了定时轮询窗口大小之外,是否有其他方法可以检测到这一点?
这个问题没有可靠的解决方法,screen.height
总是返回主监视器的高度,无论你有多少个监视器,所以这对解决问题没有任何帮助。
使用 screenX/Y 也不太有用,因为没有迹象表明一个屏幕何时结束另一个开始,并且尝试计算它将很困难,因为不能保证用户在一个屏幕上的浏览器始终位于左上角,或者浏览器占据整个屏幕,并且你无法获取除主屏幕外任何其他监视器的尺寸,因此无法知道其他屏幕的大小。
换句话说,这将是困难的,如果不是不可能的,任何解决方案都可能不是非常可靠或可移植的,因此最好只使用浏览器窗口并检测其更改,这很容易,通常也是你所需要的。
screen.availWidth
只给了我 1920
,这是主屏幕的宽度,正如我的回答所述,screen
不会为除主屏幕以外的任何屏幕提供尺寸。 - adeneo有办法,只要用户要切换到的显示器具有不同的尺寸。
我使用Angular,以下是我的做法。
在编写代码之前,请注意以下重要信息:
window.innerWidth
和window.innerHeight
是你的应用程序在浏览器中的空间大小。而window.screen.width
和window.screen.height
是运行你的应用程序的浏览器所在设备(如你的显示器或笔记本电脑屏幕)的大小。因此,如果你监听window.screen.height
和window.screen.width
的变化,你可以检测到用户是否将浏览器拖到另一个监视器上,只要该监视器具有不同的高度和/或宽度。screen.width
和screen.height
或window.screen.width
和window.screen.height
,两者都可以得到相同的结果。我们将使用screen
而不是window.screen
,因为它更短。window:resize
事件至少在Angular中触发的不仅是当用户扩展或收缩浏览器窗口时,还包括当监视器或设备的屏幕尺寸发生变化时。import { Component, OnInit, HostListener } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
screenHeight: number
screenWidth: number
constructor() {
this.screenHeight = screen.height
this.screenWidth = screen.width
}
ngOnInit(): void { }
@HostListener('window:resize', ['$event'])
onResize() {
// if user has switched from one monitor size to another, then screen.height and screen.width will have changed
if(this.screenHeight != screen.height || this.screenWidth != screen.width) {
console.log("Congratulations, this must be a different monitor/device")
this.screenWidth = screen.width
this.screenHeight = screen.height
}
}
}
device-height
和device-width
规则。你可以附加事件监听器以便在这些值改变时得到通知。也许这能帮助你。在这里阅读更多信息:https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#device-width。 - dfsq