<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/knockout-3.4.0.js" type="text/javascript" charset="utf-8"></script> <style type="text/css" media="screen"> .profitWarning{font-size:20px;color:#f00;} </style> </head> <body> <div data-bind="css: { profitWarning: currentProfit() < 0 }"> Profit Information </div> <script type="text/javascript"> var viewModel = { currentProfit: ko.observable(150000) }; ko.applyBindings(viewModel); setTimeout(function(){ viewModel.currentProfit(-50); },2000) </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/knockout-3.4.0.js" type="text/javascript" charset="utf-8"></script> <style type="text/css" media="screen"> .profitWarning{font-size:20px;color:#f00;} .profitPositive{font-size:30px;color:#0f0;} </style> </head> <body> <div data-bind="css: profitStatus"> Profit Information </div> <script type="text/javascript"> var viewModel = { currentProfit: ko.observable(150000) }; viewModel.profitStatus = ko.pureComputed(function() { return this.currentProfit() < 0 ? "profitWarning" : "profitPositive"; }, viewModel); viewModel.currentProfit(-50); ko.applyBindings(viewModel); setTimeout(function(){ viewModel.currentProfit(50); },2000); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/knockout-3.4.0.js" type="text/javascript" charset="utf-8"></script> <style type="text/css" media="screen"> .profitWarning{font-size:20px;color:#f00;} .profitPositive{font-size:30px;color:#0f0;} </style> </head> <body> <div data-bind="css: { profitWarning: currentProfit() < 0, majorHighlight: isSevere }"> <script type="text/javascript"> // div css 当currentProfit小于0时 class中有profitWarning //div css 当isSevere等于真时 class中有majorHighlight var viewModel = { currentProfit: ko.observable(150000), isSevere:true }; viewModel.currentProfit(-50); ko.applyBindings(viewModel); </script> </body> </html>
css绑定时,如果用my-class会报错,如果非要用就需要加引号
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/knockout-3.4.0.js" type="text/javascript" charset="utf-8"></script> <style type="text/css" media="screen"> .profitWarning{font-size:20px;color:#f00;} .profitPositive{font-size:30px;color:#0f0;} </style> </head> <body> <div data-bind="css: { my-class: someValue }">...</div> <script type="text/javascript"> //会报错 var viewModel = { someValue:true }; ko.applyBindings(viewModel); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/knockout-3.4.0.js" type="text/javascript" charset="utf-8"></script> <style type="text/css" media="screen"> .profitWarning{font-size:20px;color:#f00;} .profitPositive{font-size:30px;color:#0f0;} </style> </head> <body> <div data-bind="css: { 'my-class': someValue }">...</div> <script type="text/javascript"> //不会报错 var viewModel = { someValue:true }; ko.applyBindings(viewModel); </script> </body> </html>