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

时间:2013-01-25 09:59:16

标签: html css background-image

我在远程网络服务器上托管了一个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>

如果我使用浏览器的网络检查工具检查身体元素,并选择&#34;在新标签中打开图像&#34;图像就在那里。因此,浏览器完全能够使用给定的URL获取图像文件。

我是不是想尽可能地完成任务,或者这是浏览器的安全功能,试图阻止外部域访问用户的本地资源?

5 个答案:

答案 0 :(得分:18)

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

就像:

background-image: url("img1.png")

答案 1 :(得分:15)

background: url(../images/backgroundImage.jpg) no-repeat center center fixed;

这应该有帮助

答案 2 :(得分:7)

杰夫布里奇曼是对的。所有你需要的是 背景:网址(&#39; pic.jpg&#39;)
这假设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>

答案 3 :(得分:0)

你忘记了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>

答案 4 :(得分:0)

FireFox不允许打开本地文件。但是,如果您想使用它来测试其他图像(这只是我要做的事情),则可以简单地将整个页面保存在本地,然后插入url(file:///somewhere/file.png)-对我有用。