【问题标题】:Load up css conditionally from angular controller从角度控制器有条件地加载 css
【发布时间】:2016-03-29 20:54:40
【问题描述】:

我正在努力使我的网站更易于访问。我遇到的问题之一是文本/背景对比。根据规范,可以放置一个启用高对比度模式的高对比度开关。为了满足这个要求,我想在我的网站上放置一个按钮或开关,当它被激活时,会触发一个扫描文档以查找background:low-contrast 实例并将该属性替换为background:high-contrast 的功能。

我已经完成了 ng-class="{'high-contrast':highContrast}"

的工作
<button 
    ng-controller="HighContrastController" 
    ng-click="$root.highContrast=!$root.highContrast" 
    class="high-contrast-switch">
  <i class="fa text-white fa-adjust">
    <span class="sr-only">High Contrast Mode</span>
  </i>
</button> 

function HighContrastController($rootScope) {
  $rootScope.highContrast = false;
}

但我认为我更愿意在控制器中完成这一切,这将使我能够在全局范围内对所有视图应用高对比度,而不会使我的部分逻辑混乱。

我可以做到的一种方法是忘记 high-contrast 类,并应用 lightdark 类。 high contrast.css 在通过控制器加载时会对这些类应用高对比度颜色。是否有角度的方式来做到这一点,或者我应该依靠常规的 javascript 来加载 highcontrast.css?

【问题讨论】:

    标签: javascript css angularjs accessibility


    【解决方案1】:

    在某些根元素上设置一个带有 ng-class 的 'highContrast' 类,例如身体。然后,在您的 css 中,根据此类应用单独的 css 规则。

    在 css 中更改颜色仍然很麻烦,但至少您不会弄乱您的控制器、rootscope 和 html。你可以通过使用 less 或 sass 来保持你的 css 相对干净,这肯定有助于保持简单,例如通过使用变量。

    var module = angular.module('myApp', []);
    module.controller('accessibilityController', function() {});
    module.controller('someController', function() {});
    module.controller('someOtherController', function() {});
    .mainContent {
      color: blue;
    }
    .highContrast .mainContent {
      color: red;
    }
    .highContrast .custom {
      color: green;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp" ng-class="{'highContrast': highContrast}" ng-controller="accessibilityController">
      <button ng-click="highContrast = !highContrast">Switch colour</button>
      <div class="mainContent">
        <div ng-controller="someController">This simulates a partial view</div>
        <div ng-controller="someOtherController">This also simulates a partial view</div>
        <div class="custom">Customize accessibility by overriding css rules</div>
      </div>
    </div>

    【讨论】:

    • 当我的开关位于 NavBarController 的导航栏控制器内时,我得到了嵌套控制器的怪异:
    • 不确定您的确切意思,但可能需要使用 $parent.highContrast 从由 NavBarController 控制的导航栏中访问accessibilityController。否则,请解释您遇到的“怪异”:-)
    猜你喜欢
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2015-01-05
    • 2018-08-29
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多