0

当我启动我的页面时,css 完全搞砸了,因为我的 js 应该在点击时动态加载 css(移动或标准网站 css)。目前,它只是加载它们。这是代码:

function loadjscssfile(filename, filetype)
{
    if (filetype=="css")
    {
        var fileref = document.createElement("link");
        fileref.rel= "stylesheet";
        fileref.type = "text/css";
        fileref.href = filename;
        document.getElementsByTagName("head")[0].appendChild(fileref)

    }
}
loadjscssfile("HCSS.css", "css")

我在网站上有两个链接。一个加载移动 css,另一个加载标准网站 css。我有它像这样链接:

 <a href="javascript:loadjscssfile ('HCSS.css','css')"> load hcss </a>
 <br/>
 <a href="javascript:loadjscssfile ('foundation.css','css')"> load mobile </a>
4

1 回答 1

0

What you are after is swapping css files, not just loading a new one. In jquery it would probabaly look something like this (code not tested):

function swapCssFiles(fileToLoad, fileToUnload) {
  $('head link[href="'+fileToUnload'"]')   // select the tag with css to unload
      .attr('href', fileToLoad);  // swap the href attribute with the file to load
}

This is off course possible with 'pure' javascript, but I'm to much a jQuery addict to tell you how. If you see how easy the syntax is, you can probably tell why.

Your links would look something like this:

<a href="javascript:swapCssFiles ('HCSS.css','default.css')"> load hcss </a>

I hope this is helpfull.

Note however that this is not the way I would approach this. If you want to target mobile devices with specific css, I would use mediaqueries to detect screensize, and not javascript.

于 2013-01-17T19:28:33.323 回答