[英]How to change a CSS property dynamically in AngularJS
現在我有一個硬編碼到 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。 謝謝你。
您可以使用 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+')' };
}
您可以直接使用[ngStyle]
。 這是一張地圖,因此您可以直接處理其中一個元素,如下所示: [ngStyle.CSS_PROPERTY_NAME]
例如:
<div class="offer-detail-image-div"
[ngStyle.background-image]="'url(' + backgroundSrc + ')'">Hello World!</div>
此外,對於提供資產,Angular 具有bypassSecurityTrustStyle
實用程序功能,可以在動態提供資產時派上用場。
在文本框中輸入大小,您可以看到框的高度和寬度變化
<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <p>Change the value of the input field:</p> <div ng-app="" > <input ng-model="myCol" type="textbox"> <div style="background-color:red; width:{{myCol}}px; height:{{myCol}}px;"> </div> </div> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.