简体   繁体   English

从外部js文件返回样式表

[英]Return stylesheet from external js file

I'm using the JavaScript below to decide which style sheet to load (my Christmas style loads if it's December, otherwise my default style loads). 我正在使用下面的JavaScript来确定要加载的样式表(如果圣诞节是12月,则将加载圣诞节样式,否则将加载默认样式)。 This is causing problems with the XHTML validation, I suspect the best solution would be to load the js from an external file but I'm fairly new to this and can't for the life of me get this to work. 这导致XHTML验证出现问题,我怀疑最好的解决方案是从外部文件加载js,但是对此我还很陌生,并且我一生无法使它正常工作。

I'd like, if possible, to use the same code but in a separate file to achieve the same effect as having it execute directly in the HTML. 我希望,如果可能的话,使用相同的代码,但在单独的文件中使用,以达到与直接在HTML中执行相同的效果。 If someone could explain how to do this it would be much appreciated! 如果有人可以解释如何做到这一点,将不胜感激!

<head>
<script type="text/javascript">
    var i = new Date();
    var m = i.getMonth();
    if (m==11) {
        document.write('<link rel="stylesheet" type="text/css" href="mystyle-christmas.css" />');
    } else {
        document.write('<link rel="stylesheet" type="text/css" href="mystyle-default.css" />');
    }
</script>
</head>

You might wanna use the DOM functions to create a LINK node and add that to the header instead. 您可能想使用DOM函数创建LINK节点,并将其添加到标头中。

var l = document.createElement('LINK');
l.setAttribute('rel','stylesheet');
l.setAttribute('href','mystyle-christmas.css');
l.type = 'text/css';
document.getElementsByTagName('HEAD')[0].appendChild(l);
<link id="stylesheet" rel="stylesheet" type="text/css" href="mystyle-default.css" />

var i = new Date();
var m = i.getMonth();
if (m>=11) {
document.getElementById('stylesheet').href = 'mystyle-christmas.css';
} 

The default stylesheet does not need to be loaded with javascript, you only replace the stylesheet during month(s) needed. 默认样式表无需加载javascript,您只需在所需月份内替换样式表即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM