如何在 AngularJS 中动态更改 CSS 属性

新手上路,请多包涵

现在我有一个硬编码到 CSS 中的背景图片 URL。我想使用 AngularJS 中的逻辑动态选择背景图像。这是我目前拥有的:

HTML

 <div class="offer-detail-image-div"><div>

CSS

 .offer-detail-image-div {
  position: relative;
  display: block;
  overflow: hidden;
  max-width: 800px;
  min-height: 450px;
  min-width: 700px;
  margin-right: auto;
  margin-left: auto;
  padding-right: 25px;
  padding-left: 25px;
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border-radius: 5px;
  background-image: url('/assets/images/118k2d049mjbql83.jpg');
  background-position: 0px 0px;
  background-size: cover;
  background-repeat: no-repeat;
}

如您所见,CSS 中的背景图像引用了特定的文件位置。我希望能够以编程方式确定图像 URL 的位置。我真的不知道从哪里开始。我不知道 JQuery。谢谢你。

原文由 rashadb 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 312
2 个回答

您可以使用 ng-style 通过 AngularJS 动态更改 CSS 类属性。

希望这个 ng 风格的例子至少能帮助你理解这个概念。

有关 ngStyle 的更多信息

 var myApp = angular.module('myApp', []);
myApp.controller("myAppCtrl", ["$scope", function($scope) {
      $scope.colors = ['#C1D786', '#BF3978', '#15A0C6', '#9A2BC3'];
      $scope.style = function(value) {
          return { "background-color": value };
      }
}]);
 ul{
  list-style-type: none;
  color: #fff;
}
li{
  padding: 10px;
  text-align: center;
}
.original{
  background-color: red;
}
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myAppCtrl">
  <div class="container">
    <div class="row">
      <div class="span12">
        <ul>
          <li ng-repeat="color in colors">
            <h4 class="original" ng-style="style(color)"> {{ color }}</h4>
          </li>
        </ul>
      </div>
    </div>
  </div>
</div>
</body>

编辑-1

您可以通过以下方式更改 background-image: URL。

 $scope.style = function(value) {
   return { 'background-image': 'url(' + value+')' };
}

原文由 Mohit Tanwani 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 ng-class :文档。如果你想在你的 directive 检查 directive - attr : attr

原文由 Itsik Mauyhas 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题