Load different CSS stylesheet with javascript

后端 未结 2 1668
孤城傲影
孤城傲影 2021-01-16 01:30

I need to use javascript to load a different stylesheet based on a URL variable that is being passed.

The scenario is this: We need to maintain a mobile website wi

2条回答
  •  滥情空心
    2021-01-16 02:11

    You can add a CSS stylesheet by using appendChild() like this:

     var header = $.getElementsByTagName('head')[0];
     var styleSheet = $.createElement('link');
     styleSheet.rel = 'stylesheet';
     styleSheet.type = 'text/css';
     styleSheet.href = 'style.css'; // name of your css file
     styleSheet.media = 'all';
     header.appendChild(styleSheet);
    

    Of course you could change this example to accomodate different css file names depending on the current URL by doing something like this:

     styleSheet.href = (isMobile == true) ? 'mobile.css' : 'default.css';
    

提交回复
热议问题