使用style属性动态设置css变量不起作用,Angular 8

我正在尝试通过style属性将值传递给动画,但是该值的动态设置不起作用。 我使用以下文章https://css-tricks.com/css-attr-function-got-nothin-custom-properties/

作为参考

HTML:

      <div class="labelContainer">
        <p #label class="optionLabel" [ngClass]="{'optionLabel--animated': isSelected(option) && checkOverflow(label)}"
         [style]="labelOffset" >
          {{ option.label }}
        </p>
      </div>

TS:

  _labelOffset = `--labelOffset: '0px'`

  checkOverflow(label):boolean {
    if(label.offsetWidth < label.scrollWidth){
      let offset = label.scrollWidth - label.offsetWidth;
      this._labelOffset = `--labelOffset: '${offset}px'`;
      return true;
    }
      return false;
  }


  get labelOffset(){
    return this._labelOffset;
  }

CSS:

.optionLabel{
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;

  &--animated{
    animation: marquee 2s linear infinite;
    overflow: visible;
  }

  $labelOffset: var(--labelOffset);

  @keyframes marquee {
    0%{transform: translateX(0%);} 
    100% {transform: translateX($labelOffset);}
   }
}

编译的HTML:

<p _ngcontent-qfr-c26="" class="optionLabel optionLabel--animated" ng-reflect-klass="optionLabel" ng-reflect-ng-class="[object Object]" style="">very long text</p>

我尝试在传递值时使用DomSanitizer,但这不能正常工作。

xiadaohaoqing3 回答:使用style属性动态设置css变量不起作用,Angular 8

最好的例子是

https://css-tricks.com/updating-a-css-variable-with-javascript/ https://davidwalsh.name/css-variables-javascript

尝试一下。

在style.scss全局文件中提供标签

:root {
--labelOffset:0px;
}

在您的组件ts文件中如何获取变量值

let _labelOffset = getComputedStyle(document.documentElement).getPropertyValue('--my-variable-name');

本文链接:https://www.f2er.com/3028068.html

大家都在问