【问题标题】:dynamic background image with angularJS javascript带有angularJS javascript的动态背景图像
【发布时间】:2016-08-03 22:12:48
【问题描述】:

我正在将一些图像加载到 DOM 中并创建一个数组来保存这些图像。我想通过从数组中收集图像来动态更改名为 wrapper 的 div 的背景图像。 如何做到这一点?

现在我有了这个

$scope.$on('$viewContentLoaded', function() {
    $rootScope.backgroundImg="url('http://abounde.com/uploads/images/office.jpg')";   
    $rootScope.loading = false;
    console.log("about page loaded");
});

我想要这样的东西

var images =[imageObject1, imageObject2, imageObject3];  
//imageObject are already loaded and when i 
//call them inside a html div using .html(), 
//they show as <img src="source of the image"/>

$scope.$on('$viewContentLoaded', function() {
    $rootScope.backgroundImg="url('images[0]')";   
    $rootScope.loading = false;
    console.log("about page loaded");
});

我可以创建对象并将它们存储在数组中。我只需要有一种方法可以在设置 div 的背景样式的 backgroundImg 变量中使用 thsee 图像

【问题讨论】:

  • 如果你想要背景图片不要使用&lt;img /&gt;标签,使用div并使用ng-style将范围数据绑定到html属性
  • 使用ng-src 而不是src
  • 使用"url("+images[counter]+")"
  • @Daniel_L 是的,我提到了我在 dom 检查器中找到的 img 标签。我没有在我的代码中使用它。

标签: javascript jquery html css angularjs


【解决方案1】:

你可以使用ngStyle

<html ng-app  ng-style="htmlStyle">
    <!-- Html here -->
</html>

然后:

var images =[imageObject1, imageObject2, imageObject3];
var currenBackground = 0;
$scope.$on('$viewContentLoaded', function() {
    var current = currenBackground++ % images.length;
    $rootScope.htmlStyle = {
       backgroundImage: "url("+ images[current].src +")"
    };   
    $rootScope.loading = false;
    console.log("about page loaded");
});

【讨论】:

    【解决方案2】:

    首先,您需要将图像 url 数组放在范围内:

    $scope.$root.images = ['imageurl', 'imageurl1', 'imageurl2']; 
    

    在 HTML 中你需要放

    ng-style="{'background-image': 'url({{ $root.images[0] }})'}
    

    这行得通!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      相关资源
      最近更新 更多