如何在按钮倾斜时克隆 HTML 页面



单击时如何在新_blank页面中克隆HTML

btn_change_folder_style_seg

btn_change_folder_style_raw

然后内容将是

<img src="./pic/web_show/3_seg/01.jpg" alt="">
<img src="./pic/web_show/3_seg/02.jpg" alt="">

<img src="./pic/web_show/3_raw/01.jpg" alt="">
<img src="./pic/web_show/3_raw/02.jpg" alt="">

现在完整代码

<img src="./pic/web_show/3/01.jpg" alt="">
<img src="./pic/web_show/3/02.jpg" alt="">
<img src="./pic/web_show/3/03.jpg" alt="">
<input type="button" id="btn_change_folder_style_seg" value="style seg"></input>
<input type="button" id="btn_change_folder_style_raw" value="style raw"></input>
<script>
$(function() {
$('#btn_change_folder_style_seg').click(function() {
alert("style_seg")
var imagePath = $('img');
imagePath.attr('src', function(index, attr) {
if (attr) {
return attr.replace('3/', index + 1 + '_seg/');
}
});
});
$('#btn_change_folder_style_raw').click(function() {
alert("style_raw")
var imagePath = $('img');
imagePath.attr('src', function(index, attr) {
if (attr) {
return attr.replace('3/', index + 1 + '_raw/');
}
});
});
})
</script>

首先,你需要选择 HTML 标签,然后通过 cloneNode(true( 方法制作它的副本,你必须添加 true 来复制它的子级

然后,您可以根据需要编辑克隆的 HTML(删除 elm - 编辑 elm 等(

因此,您必须通过(.outerHTML(将其转换为字符串

之后,您必须创建 Blob 对象的新实例并在其中附加字符串化内容并添加文件类型

const file = new Blob([content], {type: 'text/html'}(;

然后,您将需要锚标记来创建HTML文件的下载链接

a.href = URL.createObjectURL(file(;

然后,如果您单击了按钮标签,则触发要单击的锚标记

仅此而已,我希望此片段能更清楚地阐明我的答案

// select button
const btn = document.getElementById('btn');
// add click event
btn.addEventListener('click', () => {
// Select anchor
const a = document.getElementById('a');
// select html tag
const html = document.querySelector('html');
// clone html
const clonedHtml = html.cloneNode(true);
// select elements
const body = clonedHtml.querySelector('body');
// wipe out body
body.innerHTML = '';
// create div
const div = document.createElement('div');
// add text
div.innerText = 'new div';
// append div
body.append(div);
//* append to content
let content = `<!DOCTYPE html>`;
content += clonedHtml.outerHTML;
console.log(content);
// create HTML file
let file = new Blob([content], {
type: 'text/html'
});
// add href link
a.href = URL.createObjectURL(file);
// name file
a.download = 'New.html';
// run click
a.click();
});
<div class="div1">1</div>
<div class="div2">2</div>
<button type="button" id="btn">Generate HTML file</button>
<a id="a" href="" style="display: none;"></a>

最新更新