简体   繁体   中英

Apply Theme/Dynamic CSS to a Page/any HTML Element

At some point, Users might get bored of the Style/Theme of the WEB applications .
They might think, " Only If I could make it look the way I like it "

example :

  • I myself is a user of Stack Overflow. What if I Like the Page-headerBar to look Blue/Purple
  • Page itself to have a Black background and white text color
  • ...

My need :
Not just change the class attribute but the complete CSS definition itself.
If we force the users to select from a set of Stylesheets, that would be constricting them to a small space, So I like to avoid that.

* Note * I need it in pure javascript not using any jquery plugin or any jquery script

You Can Try This Its Pure Javascript

<script>
    function applyit()
    {
        var ref = document.querySelector("#divel");
        var bdy = document.getElementsByTagName("body")[0];
        var style = (bdy.querySelector("#thm") || document.createElement("style"));
        style.setAttribute("id","thm");
        var reqCSS = prompt("Enter the CSS Body","color:#AA5533;");
        style.innerHTML = ".cus{"+reqCSS+"}";
        bdy.appendChild(style);
        ref.setAttribute("class","cus");
    }
    </script>
    <style> .def { color:#0000FF; } </style>

<div id="divel" class="def">
  <h3>This is a heading in a div element Which Has The Color Change</h3>
  <p>This is p tag in a div element Which Has The Color Change.</p>
</div>

<p onclick="applyit();">Click Here To Change The Color For Heading and p tag.</p>

Note: We could store the User Preferred style in browserStorage/Server to improve UserExperience

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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