初学者问题:
class="date{{item.isNearDueDate ? 'red' : ''}}"时动态类red不表达
解决:
在 HTML 中,当使用动态类绑定时,如果模板字符串中没有空格,那么生成的类名可能会和相邻的类名粘在一起,导致样式没有按预期生效。
例如,如果你的模板字符串是 class="date{{item.isNearDueDate ? 'red' : ''}}"
,当 item.isNearDueDate
为 true 时,它会生成一个类名为 datered
,而不是 date red
。因此,CSS 规则将不会匹配这个类名,导致样式不生效。
而当你在模板字符串中添加了空格,如 class="date{{item.isNearDueDate ? ' red' : ''}}"
,当 item.isNearDueDate
为 true 时,它会生成一个类名为 date red
,这样就能够正确匹配对应的 CSS 样式规则,从而实现预期的效果。
因此,确保在动态类名绑定时,要注意空格的位置,以使生成的类名符合预期的样式规则。
解决:
将上面代码改为:
class="date{{item.isNearDueDate ? ' red' : ''}}",在red前面加空格即可。