创建指令时不显示背景图像

background image isn't showed with the creation of the directive

本文关键字:背景 图像 显示 指令 创建      更新时间:2023-09-26

这是我的指令

(function() {
  'use strict';
  angular
    .module('app')
    .directive('backgroundImage', Background);
    function Background () {
      return function (scope, element, attrs) {
        scope.$watch(attrs.backgroundImage, function(value) {
          element.css({
            'background-image': 'url(https://example.com/' + value + '.jpg)',
            'background-repeat': 'no-repeat',
            'background-position': 'center center',
            'background-attachment': 'fixed',
            '-webkit-background-size': 'cover',
            '-moz-background-size': 'cover',
            '-o-background-size': 'cover',
            'background-size': 'cover'
          });
        });
      };
    }
}());

我使用以下代码从视图中调用

<div background-image="id"></div>

我的问题是,尽管图像已正确加载,但它并未显示在视图中。你有什么想法吗?

您还需要提供height,以使背景图像可见,如果需要,还需要宽度。由于该div 内没有内容,因此它将处于 0 高度。 如果不提及特定宽度,div块元素将占用其容器的整个宽度。

例:

      element.css({
        'background-image': 'url(https://example.com/' + value + '.jpg)',
        'background-repeat': 'no-repeat',
        'background-position': 'center center',
        'background-attachment': 'fixed',
        '-webkit-background-size': 'cover',
        '-moz-background-size': 'cover',
        '-o-background-size': 'cover',
        'background-size': 'cover',
        'height' :'200px'
      });

如果您有预设的高度和宽度,请通过 css 设置高度和宽度。如果需要使其灵活,请通过创建临时图像对象来计算高度和宽度。

scope.$watch(attrs.backgroundImage, function(value) {
        var url = 'https://example.com/' + value + '.jpg';
        getImageDimensions(url).then(function(dimObj) {
          element.css({
            'background-image': 'url(' + url + ')',
            'background-repeat': 'no-repeat',
            'background-position': 'center center',
            height: dimObj.height,
            width: dimObj.width
          });
        })
      });
      function getImageDimensions(url) {
        var defer = $q.defer();
        var img = new Image();
        img.onload = function() {
          defer.resolve({height: img.height + 'px', width:img.width + 'px'});
          img = null;
        }
        img.onerror = function(){
          defer.reject("Ivalid url");
          img = null;
        }
        img.src = url;
        return defer.promise;
      }
    };
  }