knockout.js 的CSS
示例
此绑定会将提供的CSS类应用于该元素。当将给定条件宽松地评估为true时,将应用静态类。动态类使用可观察或计算的值。
page.html
<p data-bind="css: { danger: isInDanger }">Checks external expression</p> <p data-bind="css: { danger: dangerLevel() > 10 }">Expression can be inline</p> <p data-bind="css: { danger: isInDanger, glow: shouldGlow }">Multiple classes</p> <p data-bind="css: dynamicObservable">Dynamic CSS class from observable</p> <p data-bind="css: dynamicComputed">Dynamic CSS class from computed</p>
page.js
ko.applyBindings({ isInDanger: ko.observable(true), dangerLevel: ko.observable(5), isHot: ko.observable(true), shouldGlow: ko.observable(true), dynamicObservable: ko.observable('highlighted'), dynamicComputed: ko.computed(function() { var customClass = ""; if(dangerLevel() >= 15 ) { customClass += " danger"; } if(dangerLevel() >= 10) { customClass += " glow"; } if(dangerLevel() >= 5) { customClass += " highlighted"; } return customClass; }); });
page.css
.danger { background: red; } .glow { box-shadow: 5px 5px 5px gold; } .highlighted { color: purple; }
另请参阅:官方文档。