【问题标题】:How manage to open menu with click for mobile and hover for Desktop如何通过单击移动设备和悬停桌面来管理打开菜单
【发布时间】:2020-06-19 07:36:57
【问题描述】:

我正在使用 Angular 9,我如何设法打开菜单,点击移动设备并悬停桌面设备?

例如,如果我有一个项目列表,我想在桌面大小时通过悬停打开菜单,我使用“悬停”进行管理,但是当我有移动设备时,我想通过单击打开菜单,考虑到我有不止一个按钮,所以我不想有两个不同的按钮来管理操作 问候

【问题讨论】:

标签: html css angular typescript sass


【解决方案1】:

我认为最简单和最快的方法是实现媒体查询 css,但这不是你想要的。然后,您可以创建一个管理断点的服务,并在需要的地方重用它。应该是这样的:

import { Injectable } from '@angular/core';
import { BreakpointObserver, BreakpointState, Breakpoints } from '@angular/cdk/layout';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class BreakpointsService {

  isMobile: Subject<boolean> = new Subject();

  constructor(
    private breakpointObserver: BreakpointObserver,
  ) {
    this.breakpointObserver
    .observe([
      Breakpoints.XSmall
    ])
    .subscribe((state: BreakpointState) => {
      if (state.matches) {
        // console.log('isMobile');
        this.isMobile.next(true);
      } else {
        // console.log('not isMobile');
        this.isMobile.next(false);
      }
    });
  }

  isMobile$() {
    return this.isMobile.asObservable();
  }

  isMatchedMobile() {
    const rta = this.breakpointObserver.isMatched([Breakpoints.XSmall]);
    this.isMobile.next(rta);
  }


}

在你的组件中使用如下:

this.breakpointsService.isMobile$()
  .pipe(
    takeUntil(this.unsubscribe$)
  )
  .subscribe(value => {
    this.isMobile = value;
  });

【讨论】:

    【解决方案2】:

    作为一种解决方法,您可以检查用户是使用移动设备还是桌面设备,然后将请求的功能应用到每个用户。

    使用组件上的 ngOnInit 钩子进行验证:

    ngOnInit(): void {
      if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
        // Logic for mobile users using on click
      } else {
        // Logic for desktop users using on hover
      }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-25
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      相关资源
      最近更新 更多