【问题标题】:Change div background-image randomly on page refresh using Angular js使用Angular js在页面刷新时随机更改div背景图像
【发布时间】:2021-05-25 15:45:12
【问题描述】:

由于我是使用 AngularJS 的新手,我想知道如何在页面刷新时随机更改 div background-image

提前感谢您的帮助。

【问题讨论】:

  • 你需要展示你到目前为止尝试过的代码。

标签: css angularjs twitter-bootstrap


【解决方案1】:

一个非常基本的方法应该是:-
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>

【讨论】:

    【解决方案2】:

    关于在 Angular 11 中的刷新页面上更改背景图像的有用链接。

    change background image on refresh page

    【讨论】:

      猜你喜欢
      • 2014-04-07
      • 1970-01-01
      • 2023-04-02
      • 2013-04-04
      • 1970-01-01
      • 2010-11-27
      • 2012-10-08
      • 1970-01-01
      • 2013-08-19
      相关资源
      最近更新 更多