Javascript - 一键添加和删除 CSS 文件 [英] Javascript - Add and Remove CSS file with one button
本文介绍了Javascript - 一键添加和删除 CSS 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个将 CSS 文件添加到页眉的按钮.如何通过第二次单击同一按钮从标题中删除此 CSS?
I created a button that ADD CSS file to the page header. How Can I REMOVE this CSS from the header with the second click on the same button?
谢谢
<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>
推荐答案
添加一些东西来标识样式标签,一个 ID 似乎合适
Just add something to identify the style tag, an ID seems appropriate
$(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();
}
});
});
这篇关于Javascript - 一键添加和删除 CSS 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文