我在外部 js 中有以下内容,它被推迟到页面加载之后。
var stylesheet=document.createElement("link");
stylesheet.href="soc.css";
stylesheet.rel="stylesheet";
document.getElementsByTagName("head")[0].appendChild(stylesheet);
window.___gcfg={parsetags:'onload'};
var xObj=new XMLHttpRequest();
xObj.open('GET','social.html',true);
xObj.onreadystatechange=function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById("foot").innerHTML=this.responseText;
}
};
xObj.send();
html 放置在 div 中,但 soc.css 中的 css 未应用于 div 的新内容。
有没有办法在初始加载后将 css 应用于 div。如果可能的话,我宁愿不必将所有 css 保留在页面上以进行初始加载。不使用 jQuery。
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
在这里更新
这是我的:
index.html
<div id=foot></div>
社会.css
.s{background:url(soc.png) no-repeat top left;width:32px;height:32px}
.s.s-1{background-position:0}
.s.s-2{background-position:-37px 0}
.s.s-3{background-position:-74px 0}
.s.s-4{background-position:-111px 0}
.s.s-5{background-position:-148px 0}
#sm li{display:inline-block;max-width:100%;padding:3px}
#sm{list-style:none;margin-left:-40px;text-align:center}
#ft{font-size:22px;margin:80px 0 0;text-align:center}
社交.html
<p>Join us on Google+
<hr>
<ul id=sm>
<li><a href=//plus.google.com><div class="s s-1" title=googleplus></div></a>
<li><a href=https://www.facebook.com><div class="s s-2" title=facebook></div></a>
<li><a href=https://twitter.com><div class="s s-3" title=twitter></div></a>
<li><a href=#><div class="s s-4" title=pinterest></div></a>
<li><a href=http://www.linkedin.com><div class="s s-5" title=linkedin></div></a>
</ul>
<hr>
<h1 id=ft>Hello</h1>
当我在 js 中同时运行您的或我的代码时,就会发生这种情况。来自 social.html 的 html 放在 index.html 的 div 中
来自 soc.css 的图像出现在 index.html 上正确的 div 类中
此示例中的以下 3 行从未应用:
#sm li{display:inline-block;max-width:100%;padding:3px}
#sm{list-style:none;margin-left:-40px;text-align:center}
#ft{font-size:22px;margin:80px 0 0;text-align:center}
没有控制台错误,看起来样式也没有更新。
当我点击
<ul id="sm">
这是我得到的
ul, menu, dir {
display: block;
list-style-type: disc;
-webkit-margin-before: 1em;
-webkit-margin-after: 1em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
-webkit-padding-start: 40px;
}
当我点击一个单独的 li 时,我得到了这个
li {
display: list-item;
text-align: -webkit-match-parent;
}
你的想法。
最佳答案
试试这个:
function addCss() {
var stylesheet=document.createElement("link");
stylesheet.href="soc.css";
stylesheet.rel="stylesheet";
stylesheet.type = 'text/css'
document.getElementsByTagName("head")[0].appendChild(stylesheet);
window.___gcfg={parsetags:'onload'};
}
var xObj=new XMLHttpRequest();
xObj.open('GET','social.html',true);
xObj.onreadystatechange=function(){
if(this.readyState==4&&this.status==200){
document.getElementById("foot").innerHTML=this.responseText;
addCss();
}};
xObj.send();
关于javascript - 使用javascript加载页面后将外部CSS应用于动态html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22565835/