前端框架Aurelia - Class & Style

本文介绍如何使用字符串插值或.bind/.one-time绑定元素的class属性,并解释了兼容性问题及性能注意事项。同时,还详细说明了绑定CSS字符串或对象到元素的style属性的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Class

You can bind a css string or object to an element's  style  attribute. Use the  style  attribute's alias,  css  when doing string interpolation to ensure your application is compatible with Internet Explorer and Edge.
You can bind an element's  class  attribute using string interpolation or with  .bind / .one-time .
可以用字符串插值或者.bind/.one-time绑定元素的class属性。

<template>
  <div class="foo ${isActive ? 'active' : ''} bar"></div>
  <div class.bind="isActive ? 'active' : ''"></div>
  <div class.one-time="isActive ? 'active' : ''"></div>
</template>


To ensure maximum interoperability with other JavaScript libraries, the binding system will only add or remove classes specified in the binding expression. This ensures classes added by other code (eg via classList.add(...)) are preserved. This "safe by default" behavior comes at a small cost but can be noticeable in benchmarks or other performance critical situations like repeats with lots of elements. You can opt out of the default behavior by binding directly to the element's className property using class-name.bind="...." or class-name.one-time="...". This will be marginally faster but can add up over a lot of bindings.
为了兼容其它的库,也可以用classList.add(...)添加class。这是default添加class的方法。
也可以选择不用default方法,用class-name.bind="...." or class-name.one-time="..."来添加多个绑定的class。


2.Style

You can bind a css string or object to an element's  style  attribute. Use the  style  attribute's alias,  css  when doing string interpolation to ensure your application is compatible with Internet Explorer and Edge.

可以绑定一个css string变量或者一个object到元素的style属性上。用style的别名。
直接用字符串插值添加style属性的时候,不要用style=“”而要用css="",保证兼容。

export class StyleData {
  styleString: string;
  styleObject: any;

  constructor() {
    this.styleString = 'color: red; background-color: blue';

    this.styleObject = {
      color: 'red',
      'background-color': 'blue'
    };
  }
}


<template>
  <div style.bind="styleString"></div>
  <div style.bind="styleObject"></div>
</template>


illegal的字符串插值
<template>
  <div style="width: ${width}px; height: ${height}px;"></div>
</template>


合法的字符串插值
<template>
  <div css="width: ${width}px; height: ${height}px;"></div>
</template>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值