简体   繁体   中英

How to switch between CSS files using external Javascript

I'm working on a website for my Web Design coursework and I'm writing both CSS scripts that will format the site for either a desktop browser or a mobile one, depending on whether the appropriate useragent is detected. I'm able to detect the presence of a mobile browser easily enough and the default CSS is desktop, the problem I have is switching between them. I've been told by the department's resident web programming guru that you should never place Javascript directly into the html file, and that it should all be off in external files, which so far I've been able to stick to.

Now my problem is that I can't find a way to determine which CSS file to load without using inline Javascript. The script I'm using to detect the presence of the mobile browser returns a boolean value depending on the result of checking the useragent, and I would use that to load the appropriate CSS file.

Question : How should I write a Javascript file that will load the appropriate CSS file?

My script for detecting the mobile (Android) browser is:

var deviceAndroid = "android";

function DetectAndroid()
{
   if (uagent.search(deviceAndroid) > -1)
      return true;
   else
      return false;
}

I think you can do it writing a JS function that finds the and change it as you determine the kind of device that is accessing, you can take a look of such JS here .

You can try as well loading both stylesheets via the tag and add a "media" attribute for the desktop (screen) or mobile (handheld) devices, you can take a look on this stackoverflow post

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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