首页 > 解决方案 > 如何在元素中强制状态悬停

问题描述

我有一个sidenav,当使用鼠标悬停时它会扩展,但需要强制悬停而鼠标不一定在元素上方

我需要的是,当页面启动时,它会自动启动并应用悬停,几秒钟后取消应用

.html

<div class="sidenav custom-sidenav" #sideNav>
  <div class="text-sidenav">{{text}}</div>
</div>

.css

   .custom-sidenav div {
      position: fixed;
      right: -120px; 
      transition: 0.3s; 
      padding: 15px; 
      width: 140px; 
      text-decoration: none; 
      font-size: 20px; 
      color: white; 
      border-radius: 5px 0 0 5px; 
      z-index: 100;
    }

    .custom-sidenav div:hover {
      right: 0; 
    }

    .text-sidenav {
      position: relative;
      top: 200px;
      background-color: #2196F3; /* Blue */
    }

我尝试将 ViewChild 与 elementRef 一起使用,但显示此错误

this.sideNav.nativeElement.mouseover 不是函数

我的ts

  @ViewChild('sideNav') private sideNav: ElementRef;

  @Input() text: string;
  constructor() { }

  ngOnInit() {
    this.sideNav.nativeElement.mouseover();
  }

标签: htmlcssangular

解决方案


我在@isherwood 的帮助下解决了这个问题

我建议你的计划有缺陷。无需依赖伪悬停状态,只需直接设置您想要的行为即可。使用 CSS 类

html

<div class="sidenav custom-sidenav" [class.custom-sidenav-hover]="show">
  <div class="text-sidenav">{{text}}</div>
</div>

.css

.custom-sidenav div {
  position: fixed;
  right: -120px;
  transition: 0.3s;
  padding: 15px;
  width: 140px;
  text-decoration: none;
  font-size: 20px;
  color: white;
  border-radius: 5px 0 0 5px;
  z-index: 100;
}

.custom-sidenav-hover div{
  right: 0;
}


.text-sidenav {
  position: relative;
  top: 200px;
  background-color: #2196F3;
}

我的ts

  @Input() text: string;
  @Input() cont: number;

  show: boolean;
  constructor() { }

  ngOnInit() {
    this.show = true;
    setTimeout(() => {
      this.show = false;
    }, this.cont);
  }

推荐阅读