简体   繁体   English

如何根据屏幕大小在 JavaScript 中自动运行函数

[英]How to run a function automatically in JavaScript based on screen size

I'm doing responsive web design.我正在做响应式网页设计。 When I shrink the screen down to tablet mode and click some buttons, certain CSS properties are applied(things are moved around and others are hidden).当我将屏幕缩小到平板电脑模式并单击某些按钮时,会应用某些 CSS 属性(移动内容而隐藏其他内容)。 Then when I enlarge the screen back to its desktop size.然后当我将屏幕放大回桌面大小时。 I want the properties to go back to the desktop version.我希望属性回到桌面版本。 How would I achieve that?我将如何实现这一目标?

The current behavior is that the effect of the button remains when I go back to the desktop screen ratio.当前的行为是当我回到桌面屏幕比例时按钮的效果仍然存在。 The expected behavior is that when I go back to the desktop screen ratio, the CSS for desktop applies.预期的行为是,当我回到桌面屏幕比例时,适用于桌面的 CSS。

You can access certain properties such as window.innerWidth which you can check to decide whether to run your function or not.您可以访问某些属性,例如window.innerWidth ,您可以检查这些属性来决定是否运行您的函数。

That's for JavaScript.那是针对 JavaScript 的。 If you want your CSS to be responsive to screen size, check media queries , for example:如果您希望 CSS 响应屏幕大小,请检查媒体查询,例如:

@media (min-height: 680px) {
    .someClass {
        margin: 5px;
    }
}

You can use CSS media queries.您可以使用 CSS 媒体查询。

@media screen and (max-width: 600px) and (min-width: 300px) {
  /* CSS for screen width between 300 and 600px */
}

With JavaScript, you could listen for the resize event.使用 JavaScript,您可以监听 resize 事件。

window.addEventListener("resize", function(e){
    console.log(window.innerWidth);
});

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

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