Javascript getStylesheet取决于类是否存在
如果页面中存在某个css类,我需要添加css样式表 i、 e.编辑以下JS:Javascript getStylesheet取决于类是否存在,javascript,css,function,if-statement,Javascript,Css,Function,If Statement,如果页面中存在某个css类,我需要添加css样式表 i、 e.编辑以下JS: <script> <!-- function getStylesheet() { var currentTime = new Date().getHours(); if (0 <= currentTime&¤tTime < 5) { document.write("<link rel='stylesheet' href
<script>
<!--
function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&¤tTime < 5) {
document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
}
if (5 <= currentTime&¤tTime < 11) {
document.write("<link rel='stylesheet' href='morning.css' type='text/css'>");
}
if (11 <= currentTime&¤tTime < 16) {
document.write("<link rel='stylesheet' href='day.css' type='text/css'>");
}
if (16 <= currentTime&¤tTime < 22) {
document.write("<link rel='stylesheet' href='evening.css' type='text/css'>");
}
}
getStylesheet();
-->
</script>
如果页面中存在certian类,我需要添加一个css文件,而不是上面的时间
如果class=“company”-使用company.css
如果class=“contact”-使用contact.css
如果class=“enterprise”-使用enterprise.css
如果class=“media”-使用media.css
我该怎么做?如果您正在使用jQuery,我建议您:
var myTypes = ['company', 'contact', 'enterprise', 'media'];
for (i in myTypes) {
if ($('.' + myTypes[i]).length) {
loadMyCSS(myTypes[i])
break;
}
}
你不应该这样做。这没有好处。只需将所有内容保存在一个样式表中,并根据
或
上的类更改页面上的样式即可。这里有一个简单的例子
<body class="page-company">
依此类推。如果可以使用jQuery,则可以使用以下命令确定页面上是否存在类:
if ($('.class').length){
// code
}
用.class
替换您试图查看是否存在的任何类
因此:
if ($('.company').length){
document.write("<link rel='stylesheet' href='company.css' type='text/css'>");
}
if ($('.contact').length){
document.write("<link rel='stylesheet' href='contact.css' type='text/css'>");
}
etc...
if($('.company').length){
文件。填写(“”);
}
如果($('.contact').length){
文件。填写(“”);
}
等
Superb。。。正是我需要的
if ($('.company').length){
document.write("<link rel='stylesheet' href='company.css' type='text/css'>");
}
if ($('.contact').length){
document.write("<link rel='stylesheet' href='contact.css' type='text/css'>");
}
etc...