我有一个带有 div 的页面,用户在其中输入一些信息,然后可以下载以保存副本。它正在使用 <div contenteditable="true">...</div>
并且当 html 被下载时,我希望 div 不再可编辑,以便已写入的文本保持打印状态。所以我想在下载的 html 中将 contenteditable="true"
更改为 contenteditable="false"
(并在网站上保持“真实”)。如何在下面的代码中实现它?非常感谢。
function downloadInnerHtml(filename, elId, mimeType) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
mimeType = mimeType || 'text/plain';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
link.click();
}
var fileName = 'text-' + getFormattedTime() + '.html'
function getFormattedTime() {
var today = new Date();
var y = today.getFullYear();
var m = today.getMonth() + 1;
var d = today.getDate();
return y + "-" + m + "-" + d;
}
$('#downloadLink').click(function(){
downloadInnerHtml(fileName, 'wrapper','text/html');
});
回答1
使用 Element.removeAttribute()
当用户单击下载时,您希望从 div 中删除 https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable 属性。您可以通过修改代码来做到这一点,使其调用 https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute,然后 div 会阻止进一步的编辑。
从:
var elHtml = document.getElementById(elId).innerHTML;
至:
var el = document.getElementById(elId);
el.removeAttribute("contenteditable");
var elHtml = el.innerHTML;
该代码无法作为 SO 片段正常工作,但您可以尝试此 https://jsfiddle.net/fhuteng6/ 以了解其工作原理。
更新:
OP 询问如何从页面上的所有元素中删除 contenteditable 属性,而不仅仅是一个。这很容易使用 https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll 来查找所有 contenteditable 元素并从每个元素中删除属性,如下所示:
document.querySelectorAll("[contenteditable]").forEach(function(el)
{
el.removeAttribute("contenteditable")
});
运行代码段以查看其工作原理:
removeAll.onclick = function() {
document.querySelectorAll("[contenteditable]").forEach(function(el) {
el.removeAttribute("contenteditable")
});
};
.container > div {
height: 2em;
padding: 0.5em;
margin: 0.5em;
border: 1px solid dimgray;
background-color: lightgray;
color: black;
}
.container > div[contenteditable=true] {
color: lime;
background-color: black;
}
<button id="removeAll">Remove All</button>
<div class="container">
<div contenteditable="true">A</div>
<div contenteditable="true">B</div>
<div contenteditable="true">C</div>
<div contenteditable="true">D</div>
<div contenteditable="true">E</div>
</div>
回答2
一个对我有用的解决方案是一个 onClick 事件,它临时将 contenteditable value 从“true”切换到“false”1 秒;足以将 div 下载为不可编辑的文本并使其在网站上保持可编辑。
function editableTimeout() {
var x = document.getElementById("downloadLink");
var editableDivs = document.querySelectorAll("[contenteditable=true]");
for(var i=0; i<editableDivs.length; i++)
editableDivs[i].setAttribute("contenteditable", false);
setTimeout(() => {
var editableDivs = document.querySelectorAll("[contenteditable=false]");
for(var i=0; i<editableDivs.length; i++)
editableDivs[i].setAttribute("contenteditable", true);
}, 1000);
}
回答3
以最简单的方式,我会尝试类似 👍 this )) elHtml.replace('contenteditable="true"', 'contenteditable="false"')