检测浏览器是否移动而无需重新加载页面

Click Me如果我的 flexbox 布局是移动的,我想弄清楚当您单击时如何关闭侧边栏。如果我通过已经知道它是移动的方式刷新移动模式下的浏览器,我可以关闭侧边栏isMobile,但如果用户有浏览器并将宽度缩小到移动视图,我也希望它关闭。除非页面重新加载,否则npmjs 库isMobile不知道它是移动的。感谢您的帮助!


<mat-sidenav-container class="sidebar-container">



  <mat-sidenav [(opened)]="isOpen" #sidenav id="sideNav" mode="side" ngif="filtersVisible" opened>

    <div class="loading">



    </div>

    <div id="spacing1"></div>



    <mat-nav-list>

      <div id="topLinks">


      </div>


      <div class="loading">


        <ngx-spinner id="loadingIcon" *ngIf="isLoading" type="ball-spin-clockwise" size="medium" color="#3071a9">

        </ngx-spinner>


      </div>


      <a mat-list-item class="navList"><label routerLink="/store" (click)="closeSidebar()" onclick="return false;"

          class="menuOptions" routerLinkActive="active-list-item"><a href="#">Click Me</a></label></a>

      <hr>


      </label></a>

      <hr *ngIf="this.role === 'Admin'">


    </mat-nav-list>


  </mat-sidenav>




  <mat-sidenav-content>


    <div id="spacing"></div>

    <router-outlet>

    </router-outlet>

  </mat-sidenav-content>

</mat-sidenav-container>


 closeSidebar() {

    if (this.mobile || this.tablet) {

      this.isOpen = false;

      this.store.dispatch({ type: "false" });

    }

  }


温温酱
浏览 106回答 2
2回答

红糖糍粑

试试这个:服务-&nbsp; &nbsp; &nbsp; &nbsp; import { Injectable } from '@angular/core';&nbsp; &nbsp; &nbsp; &nbsp; const SMALL_WIDTH_BREAKPOINT = 720;&nbsp; &nbsp; &nbsp; &nbsp; @Injectable({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;providedIn: 'root'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; export class ScreenSizeService {&nbsp; &nbsp; &nbsp;private mediaMatcher: MediaQueryList =&nbsp; &nbsp; &nbsp; matchMedia(`(max-width: ${SMALL_WIDTH_BREAKPOINT}px)`);&nbsp; &nbsp; &nbsp; constructor(&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; ) {}&nbsp; &nbsp; &nbsp;isScreenSmall(): boolean {&nbsp; &nbsp; &nbsp;return this.mediaMatcher.matches;&nbsp; &nbsp; }&nbsp; }&nbsp; &nbsp;&nbsp;在组件中使用:isScreenSmall: boolean;@HostListener('window:resize') onresize() {&nbsp; this.isScreenSmall= this.service.isScreenSmall();}&nbsp; constructor(private service: ScreenSizeService&nbsp; ) { }

30秒到达战场

提到的 isMobile 库依赖于用户代理字符串,所以它基本上不需要另一个页面加载。但是,通常只有移动设备支持“TouchEvent”。您可以使用它来检查它是否可能是移动设备,而无需依赖用户代理&nbsp; &nbsp; function isTouch() {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.createEvent('TouchEvent');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript