我可以使用本地文件系统中的图像作为HTML中的背景吗?

Joh*_*ren 28 html css background-image

我有一个托管在远程Web服务器上的HTML文档.我试图让网页上的一个元素使用我本地文件系统中的图像文件作为其背景图像.Chrome,Safari或Firefox没有运气(没试过IE).

这是我到目前为止尝试过的一个例子.

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///Users/username/Desktop/background.png')">
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果我使用浏览器的Web检查工具检查body元素,并选择"在新选项卡中打开图像",则图像就在那里.因此,浏览器完全能够使用给定的URL获取图像文件.

是我试图完全实现的,或者这是浏览器的安全功能试图阻止外部域访问用户的本地资源?

小智 19

看来你只能提供本地图像名称,假设它在同一个文件夹中......

它就足够了:

background-image: url("img1.png")
Run Code Online (Sandbox Code Playgroud)


Cjo*_*Cjo 17

background: url(../images/backgroundImage.jpg) no-repeat center center fixed;
Run Code Online (Sandbox Code Playgroud)

这应该有所帮助

  • OP 询问如何让他的浏览器从引用本地文件系统上的文件的远程服务器加载 HTML。我认为您的建议只有在图像也在远程服务器上时才有效。 (3认同)

pol*_*ris 8

杰夫布里奇曼是对的.你只需要
背景:url('pic.jpg')
,这假设pic与你的html在同一个文件夹中.

此外,罗伯托的答案很好.在Firefox和IE中测试过.感谢Raptor添加格式,显示完整的图片适合屏幕,没有滚动条...在文件夹f中,桌面上是这个html和图片,pic.jpg,使用您的用户ID.在下面进行那些替换:

<html>
<head>
    <style>
        body {

        background: url('file:///C:/Users/userid/desktop/f/pic.jpg') no-repeat center center fixed;

        background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
        -webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
        -moz-background-size: cover; /* optional for Firefox 3.6 */ 
        -o-background-size: cover; /* for Opera 9.5 */
        margin: 0; /* to remove the default white margin of body */
        padding: 0; /* to remove the default white margin of body */
        overflow: hidden;
             }
    </style>
</head>
<body>
hello
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


小智 1

你忘记了 file:/// 之后的 C:
这对我有用

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)