首頁  >  文章  >  web前端  >  如何使用變數在 LESS 中動態建立屬性名稱?

如何使用變數在 LESS 中動態建立屬性名稱?

Barbara Streisand
Barbara Streisand原創
2024-11-14 21:59:02848瀏覽

How can I use variables to dynamically create property names in LESS?

Using variables in property names in LESS (dynamic properties / property name interpolation)

LESS doesn't currently support dynamically inserted properties, despite some discussions on the topic on Stack Overflow.

Workaround #1: Inject Dynamically Generated Properties into Property Value

This workaround injects dynamically created properties into a hard-coded property value:

.vendors(@property, @value, @pre: ect) {
  -inj:~"@{pre}; -webkit-@{property}: @{value}; -moz-@{property}: @{value}; -ms-@{property}: @{value}; -o-@{property}: @{value}; @{property}: @{value}";
}

Workaround #2: Inject Dynamically Generated Properties into the Name of the Following Class (LESS < 1.4.0)

This workaround constructs a virtual class or ruleset that includes the vendors and recursively builds the next class:

.vendors(@property, @value, @rest:&quot;&quot;) {
  @inject:~&quot;@{rest} -webkit-@{property}: @{value}; -moz-@{property}: @{value}; -ms-@{property}: @{value}; -o-@{property}: @{value}; @{property}: @{value};&quot;;
}

.test(@nextclass){
  .vendors(transform, &quot;matrix(2,0,0,2,20,20)&quot;);
  .vendors(transform-origin,&quot;10px 10px&quot;, @inject);
  (~&quot;{@{inject}} .@{nextclass}&quot;){/*next class properties*/};
}

Workaround #3: Inject Dynamically Generated Properties into the Name of the Following Class (LESS 1.4.0+)

This version uses recursion to overcome limitations in LESS 1.4.0:

@nl: `&quot;\n\t&quot;`;

.multi(@props,@vals,@i,@inj) {
  @property: extract(@props, 1);
  @value: extract(@vals, 1);
  @inject:~&quot;@{inj}@{nl}-webkit-@{property}: @{value};@{nl}-moz-@{property}: @{value};@{nl}-ms-@{property}: @{value};@{nl}-o-@{property}: @{value};@{nl}@{property}: @{value};&quot;;
}

.multi(@props,@vals,@i,@inj:&quot;&quot;) when (@i &gt; 0) {
  @property: extract(@props, @i);
  @value: extract(@vals, @i);
  @injnext:~&quot;@{inj}@{nl}-webkit-@{property}: @{value};@{nl}-moz-@{property}: @{value};@{nl}-ms-@{property}: @{value};@{nl}-o-@{property}: @{value};@{nl}@{property}: @{value};&quot;;
  .multi(@props,@vals,(@i - 1),@injnext);
}

In LESS versions 1.6 and above, property name interpolation is implemented natively, so no workarounds are needed.

以上是如何使用變數在 LESS 中動態建立屬性名稱?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn