创建指令时不显示背景图像
background image isn't showed with the creation of the directive
这是我的指令
(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;
}
};
}
相关文章:
- 可以在这里为背景图像设置滤镜吗
- 使用 js 将背景图像设置为 HTML
- 如何使用css动画/javascript使具有背景图像的元素出现
- 循环浏览多个身体背景图像
- 背景图像顶部的滚动图像不移动
- 在pdfmake中嵌入背景图像
- 修复选择菜单时的背景图像
- 使用css()设置背景图像;不起作用
- 鼠标悬停时如何居中放大背景图像
- 强制谷歌为javascript背景图像编制索引
- 淡入不带HTML的背景图像
- 具有淡入淡出效果的全背景图像
- 未加载随机背景图像
- 背景图像前显示Javascript警报
- javascript背景图像位置循环
- CSS动画背景图像的过渡越来越暗
- "Ken Burns效应”;悬停背景图像
- 通过ID JavaScript显示随机背景图像
- JavaScript背景图像
- 带有图像和背景图像的ClipTo