
Problem:
You have a web page with a static CSS file (light.css) linked in the header. You need a seamless mechanism to switch the page's style to another CSS file (dark.css), replacing existing styles.
Solution:
To swap CSS files dynamically and apply the new style without reloading the page, you can utilize one of the following approaches:
1. Toggle 'rel=alternate' Attribute:
<code class="html"><link rel="stylesheet" href="main.css"> <link rel="stylesheet alternate" href="light.css" id="light" title="Light"> <link rel="stylesheet alternate" href="dark.css" id="dark" title="Dark"></code>
<code class="javascript">function enableStylesheet(node) {
node.rel = 'stylesheet';
}
function disableStylesheet(node) {
node.rel = 'alternate stylesheet';
}</code>2. Set and Toggle 'disabled' Property:
<code class="html"><link rel="stylesheet" href="main.css"> <link rel="stylesheet" href="light.css" id="light" class="alternate"> <link rel="stylesheet" href="dark.css" id="dark" class="alternate"></code>
<code class="javascript">function enableStylesheet(node) {
node.disabled = false;
}
function disableStylesheet(node) {
node.disabled = true;
}
document
.querySelectorAll('link[rel=stylesheet].alternate')
.forEach(disableStylesheet);</code>3. Toggle 'media=none' Attribute:
<code class="html"><link rel="stylesheet" href="main.css"> <link rel="stylesheet" href="light.css" media="none" id="light"> <link rel="stylesheet" href="dark.css" media="none" id="dark"></code>
<code class="javascript">function enableStylesheet(node) {
node.media = '';
}
function disableStylesheet(node) {
node.media = 'none';
}</code>Note:
The above is the detailed content of How to Dynamically Swap CSS Files Without Reloading the Page?. For more information, please follow other related articles on the PHP Chinese website!