Swap CSS Styles on the Fly
You want to dynamically change the CSS style of a web page, replacing one stylesheet with another. In vanilla JavaScript or jQuery, you can achieve this by including all necessary stylesheets and then selectively activating or deactivating them.
Option 1: Toggle rel=alternate
Include stylesheets with "rel=alternate" and toggle their state:
<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>
Option 2: Set and Toggle disabled
Include stylesheets with "rel=stylesheet" and "class=alternate", and toggle their "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; }</code>
Option 3: Toggle media=none
Include stylesheets with "media=none" and toggle their "media" 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>
Select a stylesheet node using getElementById, querySelector, or other methods. Use jQuery for further procession if desired. This approach allows you to switch CSS styles on the fly without reloading the page.
The above is the detailed content of How can I dynamically change CSS styles on a web page without reloading?. For more information, please follow other related articles on the PHP Chinese website!