简体   繁体   English

检测屏幕分辨率的变化,并在 javascript 中执行代码或其他代码

[英]detect a change of screen resolution, and execute a code or another in javascript

I have this doubt, I have a menu in which I run a javascript code or another depending on whether its width is greater or less than its height, works me well the first time the screen resolution is detected, but if there is a change of resolution or a change of orientation does not detect it, and despite for example of having changed to portrait orientation still executing the landscape orientation code.我有这个疑问,我有一个菜单,我在其中运行 javascript 代码或其他代码,具体取决于它的宽度是大于还是小于它的高度,第一次检测到屏幕分辨率时效果很好,但如果有变化分辨率或方向变化不会检测到它,尽管例如已更改为纵向,但仍执行横向代码。 Is there any way to solve this?有没有办法解决这个问题? regards问候

You could use an eventlistener and listen on the resize event.您可以使用事件侦听器并侦听resize事件。

window.addEventListener('resize', () => {
    // function body
});

But I think this is rather a styling issue and you should consider to use a different approach.但我认为这是一个样式问题,您应该考虑使用不同的方法。

Here is an extention of @mstruebing 's answer:这是@mstruebing 答案的延伸:

function resisePageMobile(){

  if (window.innerWidth <= 696) { //Detect mobile 
    aside.classList.remove('pc-stuff');
    aside.classList.add('mobile-stuff');
  }else{ //Detect other higher resolution screens
    aside.classList.remove('mobile-stuff');
    aside.classList.add('pc-stuff');
  }

}
resisePageMobile();//run once on page load

//then attach to the event listener
window.addEventListener('resize',resisePageMobile);

Running this function once at the start of the page is important because the resize event will not trigger until the window is getting resized so we must initialize page at the start !在页面开头运行此 function 很重要,因为在 window 调整大小之前不会触发调整大小事件,因此我们必须在开始时初始化页面!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM