简体   繁体   English

Javascript - 一键添加和删除 CSS 文件

[英]Javascript - Add and Remove CSS file with one button

I created a button that ADD CSS file to the page header.我创建了一个将 CSS 文件添加到页眉的按钮。 How Can I REMOVE this CSS from the header with the second click on the same button?如何通过第二次单击同一按钮从标题中删除此 CSS?

Thanks谢谢

<script>
$(document).ready(function(){
  $("#myButton").click(function(){
  var ls = document.createElement('link');
  ls.rel="stylesheet";
  ls.href="myCSSfile.css";
  document.getElementsByTagName('head')[0].appendChild(ls);
    });

});
</script>


<button id="myButton">Add / Remove</button>

Just add something to identify the style tag, an ID seems appropriate只需添加一些东西来标识样式标签,一个 ID 似乎合适

$(document).ready(function(){
    $("#myButton").on('click', function(){

        if ( $('#myStyle').length === 0 ) { // does not yet exist

            $('<link />', {
                id   : 'myStyle',
                rel  : 'stylesheet',
                href : 'myCSSfile.css'
            }).appendTo('head');

        } else { // exists, remove it

            $('#myStyle').remove();

        }
    });
});

In addition to the answer above you could also do this.除了上面的答案,你也可以这样做。 This code helps you to identify the link tag on the basis of the css file you included, no need to specially identify the link tag using the id attribute :此代码可以帮助您确定link的基础上标签css你包含的文件,无需使用专门标识的链接标签id属性:

<script>
$(document).ready(function(){
  $("#myButton").click(function(){


        if($("link[href*=myCSSfile]").length){
            $("link[href*=myCSSfile]").remove();
        }
        else{
            var ls = document.createElement('link');
            ls.rel="stylesheet";
            ls.href="myCSSfile.css";
            document.getElementsByTagName('head')[0].appendChild(ls);
        }
    });

});
</script>


<button id="myButton">Add / Remove</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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