Html Angular 2 从资产文件夹加载 CSS 背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42802431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:30:12  来源:igfitidea点击:

Angular 2 Load CSS background-image from assets folder

htmlcssangular

提问by ErnieKev

My folder structure looks like

我的文件夹结构看起来像

-myapp
    -assets
        -home-page-img
            -header-bg.jpg
    -src
        -app
        -home-page
            -home-page.component.css
            -home-page.component.html
            -home-page.component.ts

Inside my home-page.component.css, I have the following

在我的 home-page.component.css 中,我有以下内容

header {
    width: 200px;
    height: 200px;
    background-image: url('/src/assets/home-page-img/header-bg.jpg');
}

My angular-cli.json
    "assets": [
    "assets",
    "favicon.ico"
]

When I run the code, I get

当我运行代码时,我得到

GET http://localhost:4200/src/assets/home-page-img/header-bg.jpg 404 (Not Found)

For demonstrating purpose, If I change background-image to the following, I get a whole different error

出于演示目的,如果我将背景图像更改为以下内容,则会出现完全不同的错误

background-image: url('assets/home-page-img/header-bg.jpg');

./src/app/home-page/home-page.component.css
Module not found: Error: Can't resolve './assets/home-page-img/header-bg.jpg' in '/Users/JohnSmith/Desktop/my-app/src/app/home-page'

How can I get that image to load?

我怎样才能加载该图像?

回答by Thyagarajan C

try

尝试

background-image: url('../../assets/home-page-img/header-bg.jpg');

回答by Samuel Ivan

I use it. Always starting with "/assets/" in CSS and HTML "assets/". And I have no problems. Angular recognizes it.

我用这个。CSS 和 HTML 中的“assets/”总是以“/assets/”开头。我没有问题。Angular 可以识别它。

CSS

CSS

.descriptionModal{
    background-image: url("/assets/img/bg-compra.svg");
}

HTML

HTML

<img src="assets/img/ic-logoembajador-horizontal.svg" alt="logoEmbajador">

回答by Hieu Tran AGI

For background-image: url(/assets/images/foo.png), I have another problem with i18n + base-href, finally I found a workaround solution.

对于background-image: url(/assets/images/foo.png),我还有一个 i18n + base-href 的问题,最后我找到了一个解决方法

My problem was solved by:

我的问题是通过以下方式解决的:

background-image: url(~src/assets/images/foo.png).

background-image: url(~src/assets/images/foo.png).

image tag:

图片标签:

<img src="assets/images/foo.jpg" />

回答by Enetty

Try to use this below:

尝试在下面使用它:

background-image: url('./../assets/home-page-img/header-bg.jpg');