【问题标题】:How to pass variable to css in Angular如何在Angular中将变量传递给css
【发布时间】:2019-12-05 17:35:35
【问题描述】:

我正在运行 Angular 应用程序,我计算元素的宽度并将其存储在变量 finalposition 下,我想向左 (finalposition)px 移动。我希望仅在将鼠标悬停在元素上时应用此样式属性。如何做到这一点?

component.ts


 ngAfterViewChecked(): void {
    this.finalposition = document.getElementById('spandiv').offsetWidth;
  }

component.html


  <input id="inputCustome" type="text">
  <p id="spandiv">xyzkskssss</p> 

component.css

#inputCustomer {
  text-align: center;
  position: relative;
  bottom: 7px;
  left: 2px;
}


#spandiv {
  position: absolute;
  right:145px;
  top: 40px;
  background-color: #6B6664;
  padding: 5px;
  color:white;
  font-weight: normal;
  display: block;
  opacity:0;
  overflow: hidden;

}


 #inputCustomer:hover + #spandiv {
  position: absolute;
  left: var(--finalPosition*2)+ "px"; // this value is not getting picked up
  top:40px;
  display: inline;
  opacity:1;

}  

【问题讨论】:

  • 嗨,如何仅在悬停时应用 ngStyle
  • 你试过解决方案了吗?

标签: javascript html css angular typescript


【解决方案1】:

您可以使用(mouseenter)(mouseleave) 来设置finalPosition 的值。

试试:

<input id="inputCustome" type="text" (mouseenter)="finalPosition = finalPosition * 2" (mouseleave) ="finalPosition = finalPosition /2">
<p id="spandiv" [style.left]="finalPosition + 'px'" >xyzkskssss</p>

<input id="inputCustome" type="text" (mouseenter)="finalPosition = finalPosition * 2" (mouseleave) ="finalPosition = finalPosition /2">
<p id="spandiv" [ngStyle]="{'left': finalPosition + 'px'}" >xyzkskssss</p>

Demo

【讨论】:

    【解决方案2】:

    您可以利用 Angular 指令的强大功能来执行此类操作。您还可以使用 Angular 事件,例如 mouseovermouseenter。例如。

    <input id="inputCustome" type="text" (mouseover)="onMouseOver()">
    

    或者你可以使用类似的指令

    <div styleHover >Hover me</div>
    
    
    @Directive({
      selector: '[styleHover]'
    })
    export class StyleOnHover {
    
      constructor(private el: ElementRef) {}
    
      @HostListener('mouseover') onHover(e) {
        console.log(e)
        console.log(this.el);
        // this.el.style => change the property
      }
    }
    

    【讨论】:

    • 我非常喜欢这种方法。
    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 2013-08-28
    • 2013-07-31
    相关资源
    最近更新 更多