gpt4 book ai didi

javascript - 使用Javascript将所有html内容替换为base64图像

转载 作者:太空宇宙 更新时间:2023-11-04 16:17:43 25 4
gpt4 key购买 nike

我正在寻找一种使用 JS 将 HTML 文档的全部内容替换为单个图像的方法,该图像的源是 base64 字符串。

当您直接在浏览器中加载 URL 时,它在显示时会表现出某些属性。例如,图像会按纵横比缩放以适应,直到单击图像将其放大(如果图像大于窗口大小)。

但是,如果我只是做类似的事情......

document.write('<img src="data:image/png;base64,..." />');

...图像将显示,但由于缺乏更好的术语,它不会表现出那些“ native ”特征。

有没有办法告诉浏览器将其所有内容替换为 Base64 编码的图像?或者,也许有某种方式来尽可能接近地模仿 native 图像行为?

最佳答案

您不应该使用 document.write。首先,它会导致您遇到的问题。其次,它缓慢且不安全。尽可能使用 DOM,如下所示:

// Store list of all child elements
var list = document.body.children;
// Loop through list
for (var i = 0; i < list.length; i++) {
// Use native DOM method to remove child
document.body.removeChild(list[i]);
}
// Use native DOM method to create an image element
var img = document.createChild('IMG');
// Set the src of that image to your string
img.src = 'base64string';
// Use native DOM method to append image to document body
document.body.appendChild(img);

关于javascript - 使用Javascript将所有html内容替换为base64图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40942711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com