我只想在我按下 css 按钮时带上图像,但图像没有出现。这有什么问题吗?
<html>
<head>
<script >
function create() {
var x = document.createElement("IMG");
x.setAttribute("src", "C:\Users\jai guru umesh\Desktop\webops\sha\fronthead images\rover0.png");
document.body.appendChild(x);
};
</script>
</head>
<body>
<input type="button" name="cssandcreate" id="cssandcreate" value="css" onclick="create()"/>
</body>
</html>
最佳答案
您的错误在 setAttribute 函数中,您不能在 Web 浏览器中使用这种路径,因为它可以在客户端的 PC 上运行,这意味着您可以访问他们的存储,这将是一个巨大的隐私问题。
您应该使用本地文件中的图像,可以与此 html 文件位于同一文件中,也可以位于子文件夹中,例如.../img
(其中 ...
是包含 html 文件的文件夹)。然后你可以使用相对路径:
x.setAttribute("src", "img/rover0.png"); // this should work on any system
您也可以对 Windows 路径使用 /
,但是如果您要使用 \
,请确保使用 \\
。
但是如果你坚持绝对文件路径,使用这个:
x.setAttribute("src", "file:///C:\\Users\\jai guru umesh\\Desktop\\webops\\sha\\fronthead images\\rover0.png");
注意 file:///
和 \\
的使用(使用 /
代替 \\
应该也能工作)
关于javascript - 通过javascript获取图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23170973/