🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## WeX5数据绑定05:css绑定 css绑定(bind-css)为元素添加或删除class,从而改变元素的样式。css绑定非常有用,可以根据数据动态改变元素的样式,比如负值用红色来显示。另外还有一种更直接的改变样式的方法,即通过style绑定。 ### 静态class的css绑定 示例代码: //.w片段 //&lt; 是<的转义符</pre> <div bind-css="{ profitWarning: currentProfit.get() &lt; 0 }"> Profit Information </div> //.js片段 //初始正值,"profitWarning" class不会被应用到div上 this.currentProfit = justep.Bind.observable(15000); //设置负值,"profitWarning" class将会被应用到div上 this.currentProfit.set(-50); 上面这段代码,根据currentProfit的值会动态改变样式。如果currentProfit<0,就会在div添加样式class “profitWarning”,否则就会移除该class。 绑定规则: 静态class的css绑定通常都是需要判断完成的,如果表达式的返回值为true,则添加该class,如果为false,则移除该class。 ### 动态class的css绑定 如果css绑定的值是字符串,则css绑定将会直接把该字符串值作为样式设置到元素class上。 //.w片段 <div bind-css="profitStatus">Profit Information</div> //.js片段 this.currentProfit = justep.Bind.observable(15000); this.currentProfit.set(-50); this.profitStatus = justep.Bind.computed(function() { return this.currentProfit.get() < 0 ? "profitWarning" : "profitPositive"; }, this); 上面例子profitStatus属性返回的字符串”profitWarning” 或 “profitPositive”会直接作为class设置到元素上,这就是动态class的css绑定。这个特性非常灵活强大,在某些需要需求场景下非常有用。 ### 绑定多个class css绑定可以同时绑定多个class,每个class之间用半角逗号隔开,示例代码如下: //.w片段 <div bind-css="{ profitWarning: currentProfit.get() &lt; 0, majorHighlight: isSevere }"> ### 绑定不符合标识符规则的class //.w片段 <div bind-css="{ my-class: someValue }">...</div> my-class不符合javascript标识符规则,导致绑定出错。在这种情况下,可以在class用单引号引起即可,代码如下: //.w片段 <div bind-css="{ 'my-class': someValue }">...</div> ### 在固定的class之后追加绑定class //.w片段 <a component="$UI/system/components/justep/button/button" class="btn" bind-css="{ 'btn-danger': currentProfit.get() &lt; 0 }" label="button" xid="button1"> <i/> <span/> </a> 上面示例代码标签有固定的class ‘btn’,通过bind-css动态追加和移除’btn-danger’ class.