gpt4 book ai didi

javascript - 使用 InnerHTML 加载 html 页面时保持 CSS 样式

转载 作者:行者123 更新时间:2023-11-28 18:22:03 25 4
gpt4 key购买 nike

使用下面的代码,我可以通过单击菜单中的链接将 HTML 页面加载到我站点中的 div。

现在,问题是当它将 HTML 页面加载到 div 中时,它加载得很好......但是没有它应该与 HTML 页面的其他内容一起加载的原始背景颜色。所有其他 CSS 元素似乎都很好。

先谢谢你。

js代码:

function processAjax(url) 
{
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv;
try {
req.open("GET", url, true);
}
catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv;
req.open("GET", url, true);
req.send();

}
}
return false;
}

function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("containerDiv").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}

HTML:

<a onclick="return processAjax(this.href)"  href="example.html">CLICK ME</a>
<div id="containerDiv"></div>

最佳答案

从页面中获取样式元素并将其追加到头部:

var styles = document.getElementsByTagName('style');
var head = document.getElementsByTagName('head')[0];

for(var x = 0; x < styles.length; x++){
head.appendChild(styles[x]);
}

编辑:

你想先将返回的html设置为一个元素:

var div = document.createElement('div');
div.innerHTML = req.responseText;
var styles = div.getElementsByTagName('style');
for(var x = 0; x<styles.length;x++){
document.getElementsByTagName('head')[0].appendChild(styles[x]);
}

使用新代码,而不是旧代码,并将其放在 if(reg.status == 200) block 中。

关于javascript - 使用 InnerHTML 加载 html 页面时保持 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16614311/

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