如何使用JQuery在不同的样式表之间切换

How to switch between different stylesheets using JQuery?

本文关键字:样式 之间 何使用 JQuery      更新时间:2023-09-26

我正试图使用JQuery根据显示的大小更改浏览器的大小,但它目前似乎不起作用。

HTML代码:

   <head>
        <link rel="stylesheet" type="text/css" href="SmallDesktopScreen.css">
        <link id="newSize" rel="stylesheet" type="text/css" href="LargeScreen.css">
        <meta charset="UTF-8">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>
        function adjustStyleSheet(width){
        width= parseInt(width);
        if ((width>=1352)&&(width<=1880)){
            $("#newSize").attr("href", "css/SmallDesktopScreen.css");
        }
        else if(width>1881){
            $("#newSize").attr("href", "css/LargeScreen.css");
        }
        }
        <!-- 1352 1881 -->
        $("document").ready(function(){
            $(function() {
                adjustStyleSheet($(this).width());
                $(window).resize(function() {
                adjustStyleSheet($(this).width());
                });
            });
        });

可以使用jquery切换样式表。

例如

var stylesheets = ['style1.css','style2.css'];
var primary_sheet = 0;
if(primary_sheet === 0) {
  $('link').attr('href',stylesheets[0]);
else {
 $('link').attr('href',stylesheets[1]);
}

更改一些脚本就可以了。

首先,你不能,获取链接元素并设置href(这最终不会在所有浏览器中都起作用)。但你可以很容易地创建一个。

请检查下面的脚本代码。这会奏效的。

function adjustStyleSheet(width){
    width= parseInt(width);
       var head  = document.getElementsByTagName('head')[0];
        var link  = document.createElement('link');
        link.id   = "";
        link.rel  = 'stylesheet';
        link.type = 'text/css';
        link.media = 'all';
                var linkHref = "css/SmallDesktopScreen.css";
    if ((width>=1352)&&(width<=1880)){
                linkHref = 'css/SmallDesktopScreen.css';
    }
    else if(width>=1881){
                linkHref = 'css/LargeScreen.css';
    }
        link.href = linkHref;
            head.appendChild(link);
    }
    <!-- 1352 1881 -->
    $("document").ready(function(){
        $(function() {
            adjustStyleSheet($(window).outerWidth());//OuterWidth gets the width of your original screen size not the window size alone.
            $(window).resize(function() {
                adjustStyleSheet($(window).outerWidth());
            });
        });
    });

用Javascript或jQuery做事情是很好的。但我会支持CSS中的@media查询,以实现响应式的工作,这实际上非常容易。