【问题标题】:Angular 5: Use ngClass to switch classes for mobile and desktop viewsAngular 5:使用 ngClass 切换移动和桌面视图的类
【发布时间】:2018-10-07 17:31:29
【问题描述】:

我的应用程序使用这些类:“large-screen”用于桌面视图,“small-screen”用于移动视图。我正在尝试使用 ngClass,以便可以在容器或包装器 div 中为各种组件在这些类之间切换,但我的所有实现似乎都不起作用。 p>

要求是桌面视图切换到“大屏幕”,移动视图切换到“小屏幕”。 以下是已经存在的媒体查询。

@media only screen and (max-width: 415px) {
  .large-screen {
    display: none;
  }
}
@media only screen and (min-width: 415px) {
  .small-screen {
    display: none;
  }
}

如果有人能提出不同的建议,将不胜感激。

【问题讨论】:

  • 只创建 1 个类并在媒体查询中更改其属性如何?

标签: angular css angular5


【解决方案1】:

在 app.ts 中

  addclass:any
  ngOnInit(){
    if (window.innerWidth < 658) {
    this.addclass =true
    alert("hgjk")
    } else {
     this.addclass=false
    } 
  }

在 html 中使用 ngClass

<div [ngClass]="{'table-striped':addclass}">
</div>

【讨论】:

    【解决方案2】:

    您可以通过简单的媒体查询和 HTML 的类属性来实现。不需要去 ngClass。

    CSS

    @media only screen and (max-width: 415px) {
      .small-screen {
        display: block;
      }
      .large-screen {
        display: none;
      }
    }
    @media only screen and (min-width: 415px) {
      .small-screen {
        display: none;
      }
      .large-screen {
        display: block;
      }
    }
    

    HTML

    <div class="small-screen large-screen"></div>
    

    【讨论】:

    • 您只是复制了我的部分答案。呵呵
    • @CassianoMontanari 似乎但我没有,实际上我没有看一眼你的答案。巧合的是,我从问题中复制了 CSS 部分,并简单地输入了“display:none/block”。如果你愿意,我可以删除我的答案
    【解决方案3】:

    您只能创建 1 个类并根据媒体查询更改其属性,如下所示:

    @media only screen and (max-width: 415px) {
      .class-name {
        background-color: blue;
      }    
    }
    @media only screen and (min-width: 415px) {
      .class-name {
        background-color: red;
      }
    }
    

    否则,您将不得不 display:none 媒体查询中的类,您不希望它们出现,如下所示:

    @media only screen and (max-width: 415px) {
      .small-screen {
        display: block;
      }
      .large-screen {
        display: none;
      }    
    }
    @media only screen and (min-width: 415px) {
      .small-screen {
        display: none;
      }
      .large-screen {
        display: block;
      }
    }
    

    这样你就必须在你想要在两个设备上工作的所有 div 中都使用它们:

    &lt;div class="small-screen large-screen"&gt;&lt;/div&gt;

    如果你想根据变量值使用,那么 ngClass 是有意义的,你可以这样使用:

    &lt;div [ngClass]="{'small-screen': isMobile, 'large-screen': !isMobile}&gt;&lt;/div&gt;

    【讨论】:

    • Cassiano Montanari 感谢您的回答。在最后一个选项中,我还需要为[ngClass]="{'small-screen': isMobile, 'large-screen': !isMobile} 声明display:none 吗? isMobile 的值也应该像 max-width: 415px 一样指定吗?
    • 所以,对于最后一个选项,两个类都有 display:block,但是你必须在 javascript/typescript 上创建一个函数来确定设备是否是移动的,你可以使用这个答案: stackoverflow.com/questions/11381673/detecting-a-mobile-browser
    • 是否还需要将isMobile 声明到组件的打字稿中?
    • @Rich 如果它只是基于屏幕大小的你不需要变量,所以你可以使用第一个例子,如果你使用任何方法来识别设备,那么 isMobile 应该声明在javascript/打字稿。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    相关资源
    最近更新 更多