如何设置本地文件的背景图片url?

我想将相对图像 url 粘贴到 div 以将其设置为背景图像。不幸的是 div 不会渲染图像。所以这工作正常并渲染图像

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

但这个没有

<div style="background-image: url(../assets/images/HeroImg.jpg)">
    Content goes here
    </div>

我也尝试过的事情:

  • 将 url 括在单引号内

  • assets/images/HeroImg.jpg或许?

  • ./assets/images/HeroImg.jpg从src文件夹开始

  • images/HeroImg.jpg./images/HeroImg.jpg从资产文件夹开始

用于背景图像的正确网址是什么?


更新

我使用的是 VueJs,所以这里的情况可能会有所不同?重现步骤:

  • 使用 Vue CLI 创建新项目

  • 在中创建一个images目录src/assets

  • 创建一个图像src/assets/images并调用它HeroImg

  • 更新 App.vue 文件

<template>

  <div id="app">

    <div>

      This works:

    </div>

    <div>

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

    </div>

    <div>

      This doesn't work:

    </div>

    <div style="background-image: url('./assets/images/HeroImg.jpg')">

        Content without background image

    </div>

  </div>

</template>

您将看到 img 标签渲染图像,但不渲染带有背景图像的 div。


慕田峪4524236
浏览 124回答 5
5回答

慕森卡

需要在url标签内容周围添加一组额外的括号:computed: {  heroImage() {    return {      backgroundImage: `url(${require('../assets/images/HeroImg.jpg')})`    };  }}

郎朗坤

当您使用相对路径时,如果在内联属性中找到它们,Webpack 将无法正确解析它们style。但是,如果直接将图像路径用作<img>模板中的元素源,Webpack 可以正确解析图像路径。因此,使用解析的图像路径作为 CSS 属性的解决方案是简单地将其作为计算属性引用。在模板中,您可以用来v-bind:style="heroImage"引用计算属性:<template>&nbsp; <div id="app">&nbsp; &nbsp; <div v-bind:style="heroImage">&nbsp; &nbsp; &nbsp; &nbsp; Content without background image&nbsp; &nbsp; </div>&nbsp; </div></template>然后,在您的 VueJS 组件本身中,您可以执行以下操作:computed: {&nbsp; heroImage() {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; backgroundImage: `url${require('../assets/images/HeroImg.jpg')}`&nbsp; &nbsp; };&nbsp; }}

鸿蒙传说

您应该用引号将它们括起来。从MDN来看,我们需要将图像的路径或 url 包装成背景图像:url(“../../media/examples/lizard.png”);<div style="background-image: url(../assets/images/HeroImg.jpg)">     Content goes here</div>建议:最好避免使用内联样式。您可以将样式包含在外部工作表中。

明月笑刀无情

像这样在 css 文件中尝试background-image:&nbsp;url('~src/assets/home-page-img/header-bg.jpg');

回首忆惘然

html<div class="yourDivClass">&nbsp; &nbsp; Content goes here</div>CSS.yourDivClass {&nbsp; background: url('../assets/images/HeroImg.jpg') no-repeat center center / cover}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5