Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript getStylesheet取决于类是否存在_Javascript_Css_Function_If Statement - Fatal编程技术网

Javascript getStylesheet取决于类是否存在

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&&currentTime < 5) { document.write("<link rel='stylesheet' href

如果页面中存在某个css类,我需要添加css样式表

i、 e.编辑以下JS:

<script>
<!--
function getStylesheet() {
      var currentTime = new Date().getHours();
      if (0 <= currentTime&&currentTime < 5) {
       document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
      }
      if (5 <= currentTime&&currentTime < 11) {
       document.write("<link rel='stylesheet' href='morning.css' type='text/css'>");
      }
      if (11 <= currentTime&&currentTime < 16) {
       document.write("<link rel='stylesheet' href='day.css' type='text/css'>");
      }
      if (16 <= currentTime&&currentTime < 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...