我正在运行有角度的应用程序,我计算元素的宽度并将其存储在变量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;

}

最佳答案

您可以使用(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

10-06 01:13