【发布时间】:2021-05-25 15:45:12
【问题描述】:
由于我是使用 AngularJS 的新手,我想知道如何在页面刷新时随机更改 div background-image。
提前感谢您的帮助。
【问题讨论】:
-
你需要展示你到目前为止尝试过的代码。
标签: css angularjs twitter-bootstrap
由于我是使用 AngularJS 的新手,我想知道如何在页面刷新时随机更改 div background-image。
提前感谢您的帮助。
【问题讨论】:
标签: css angularjs twitter-bootstrap
一个非常基本的方法应该是:-
1.) 在控制器中声明一个数组,其中包含图像文件的名称。
2.) 将数组的长度分配给一个变量。
3.) 生成一个介于 0 到数组 1 长度之间的随机数,因为大多数时候我们假设数组从索引 0 开始。
4.) 然后将随机数存储在一个变量中并在您的 HTML 页面中使用它。
所以 index.html:-
<html ng-app='myapp'>
<body ng-controller='myctrl'>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div style="background:url('img/{{item[rand]}}.png'); padding: 100px;">{{item[rand]}}</div>
</body>
</html>
你的 app.js:-
<script type="text/javascript">
var app = angular.module('myapp',[]);
app.controller('myctrl',function($scope){
$scope.item = ['dairy','discount','cleaning-spray']; //Declare a array which contains various colors
$scope.val=$scope.item.length; //assign the length of array to a variable
$scope.rand = Math.floor(Math.random()*$scope.val); // generate a random no . and make use of it as index of array
//console.log($scope.rand);
});
</script>
【讨论】:
关于在 Angular 11 中的刷新页面上更改背景图像的有用链接。
【讨论】: