我想使用表单更改另一个 HTML 文件的 CSS 样式。这是我到目前为止得到的,但是代码不起作用,因为它不会改变上传的 HTML 文件的样式。
这是我的主要代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Changing the style of another HTML File</title>
<script type="text/javascript">
function updateSize() {
var nBytes = 0,
oFiles = document.getElementById("uploadInput").files,
nFiles = oFiles.length;
for (var nFileId = 0; nFileId < nFiles; nFileId++) {
nBytes += oFiles[nFileId].size;
}
var sOutput = nBytes + " bytes";
// optional code for multiples approximation
for (var aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
}
// end of optional code
document.getElementById("fileNum").innerHTML = nFiles;
document.getElementById("fileSize").innerHTML = sOutput;
}
function extract() {
var el = document.getElementById("test");
el.style.background = 'green';
el.style.color = 'red';
}
</script>
<body onload="updateSize();">
<form>
<p><input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple> selected files: <span id="fileNum">0</span>; total size: <span id="fileSize">0</span></p>
<p><input type="button" value="Submit" onclick="extract()"></p>
</form>
</body>
</html>
正在上传的文件:
<html>
<head>
<style>
#test {
background-color: blue;
color: yellow;
};
</style>
</head>
<body>
<div id="test">This is a div</div>
</body>
</html>
我哪里错了?
最佳答案
你误会了什么document
指的是文件上传的工作方式。你的extract
当用户按下按钮时,函数确实被调用。 (虽然在没有文件的时候可能会被按下,那怎么办呢?)
但即使在函数内部,document
仍然指代相同的 document
, 带有 <title>Changing the style of another HTML File</title>
的那个和文件输入表格。它会查找 ID 为 #test
的元素,它无法在此 document
中找到,然后失败,因为它无法设置 style
不存在的属性/null
元素。
您似乎想要做的是:
- 让用户通过表单输入提供 HTML 文件。
- 将上传的文件解析为 HTML。
- 编辑其中包含的 CSS(包括首先解析 CSS,然后编辑它,然后重新编码它。)
- 保存文件。
这些都不简单,而且都有其微妙之处。解析 HTML 很困难,但是有一些库可以为您解决这个问题。 CSS 也是如此。保存是另一个问题——你想创建另一个用户可以下载的文件吗?您不能修改用户的文件——考虑一下网站是否可以简单地修改您硬盘上的内容。这将是一场安全灾难。
也许您应该问自己的最重要的问题是 – 为什么要这样做?
关于javascript - 使用表单更改另一个 HTML 文件的 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48609531/