function getTextContent(element) {
let text = "";
const childNodes = element.childNodes;
for (let i = 0; i < childNodes.length; i++) {
const node = childNodes[i];
if (node.nodeType === Node.TEXT_NODE) {
text += node.textContent;
} else if (node.nodeType === Node.ELEMENT_NODE) {
text += getTextContent(node);
}
}
if (text == "删除试题" || text == "编辑试题 " || text.includes("|")) {
return "";
}
return text;
}
window.onload = function () {
const content = document.getElementById("form1");
const downloadBtn = document.getElementById("downloadBtn");
downloadBtn.addEventListener("click", () => {
let indexsum=0
const textContent = getTextContent(content);
let textvalue
textvalue = textContent.replace(/\s+/g, "");
textvalue=textvalue.replace(/([0-9]{1,3}\.){2,3}/g, (match) => {
let title=match.split('.')
return "<br>//题目 " + title[0] + "<br>";
});
textvalue= textvalue.replace(/([A-Z]{1,}:)/g, (match) => {
return '<br>['+match.slice(0,1)+'].';
});
textvalue = textvalue.replace(/:/g, "");
textvalue= textvalue.replace(/单选题|多选题|填空题|判断题/g, (match) => {
indexsum+=1
return '//段落'+indexsum+'<br>'+match;
});
textvalue= textvalue.replace(/参考答案:/g, (match) => {
return `<br>[答案]`;
});
textvalue= textvalue.replace(/详细解答:/g, (match) => {
return `<br>[题解]`;
});
textvalue= textvalue.replace(/分值/g, (match) => {
return `<br>[分值]`;
});
textvalue= textvalue.replace(/分<br>/g, (match) => {
return `<br>`;
});
// const html = content.innerHTML;
const converted = htmlDocx.asBlob(textvalue);
const url = window.URL.createObjectURL(converted);
const link = document.createElement("a");
link.href = url;
link.download = "试卷.doc";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
});
};
/**
* @desc 从URL取得base64
* @param {url} String 网址
* @param {callback} Function 如果能打开图片,参数为打开图片的blob,如果不能打开图 片,参数为null
* @return void
*/
function getBase64(url,callback) {
const xhr = new XMLHttpRequest();
xhr.responseType='blob'
xhr.onload = () => {
const blob=xhr.response;
var reader = new FileReader();
reader.onload = function (e) {
callback(reader.result);
}
reader.readAsDataURL(blob);
};
xhr.onerror = (err) => {
callback(null)
};
xhr.open('GET', url, true);
xhr.send(null);
}
let img=images[i];
let url=img.src;
getBase64(url,function(base64){
if(base64==null){
img.remove();
_iterate(i);
}else {
img.src=base64;
_iterate(++i);
}
})
【html转word案例】
于 2024-03-14 10:58:36 首次发布