Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

How to make changeable themes using CSS and JavaScript

I'm pretty new to CSS and JavaScript and I was wondering if you could make a script that allows you to change what stylesheet the site uses.

Say: you had a green theme where everything is shades of green. What would you do so the user can change it to red with the press of a button?

Has anyone any idea how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can set an Id to the link tag and switch the css at runtime.

HTML

<link type="text/css" rel="stylesheet" media="all" href="../green.css" id="theme_css" />

JS

document.getElementById('buttonID').onclick = function () { 
    document.getElementById('theme_css').href = '../red.css';
};

Quick Demo:

    $( "#datepicker" ).datepicker();

$('button').button().on('click', function () {
  let linkHref = 'https://code.jquery.com/ui/1.11.4/themes/{THEME}/jquery-ui.css';

if ($('#swapTheme').prop('href').indexOf('pepper-grinder') >= 0) {
    $('#swapTheme').prop('href', linkHref.replace('{THEME}', 'black-tie'));
  } else {
    $('#swapTheme').prop('href', linkHref.replace('{THEME}', 'pepper-grinder'));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
              crossorigin="anonymous"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/pepper-grinder/jquery-ui.css" id="swapTheme" rel="stylesheet">
<div id="datepicker"></div>
<button style="padding: 5px 15px;"> Switch Theme </button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...