如何在 Angular 中将变量传递给 css

kar*_*sys 2 html javascript css typescript angular

我正在运行角度应用程序,我计算元素的宽度并将其存储在变量最终位置下,我想移动到左侧(最终位置)px。我希望此样式属性仅在将鼠标悬停在元素上时应用。这个怎么做?

组件.ts


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

Run Code Online (Sandbox Code Playgroud)

组件.html


  <input id="inputCustome" type="text">
  <p id="spandiv">xyzkskssss</p> 
Run Code Online (Sandbox Code Playgroud)

组件.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;

}  

Run Code Online (Sandbox Code Playgroud)

Adr*_*rma 5

您可以使用(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>
Run Code Online (Sandbox Code Playgroud)

或者

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

演示