search
HomeWeb Front-endCSS TutorialHow to realize multi-style selection and real-time switching of styles_Experience exchange

when we make a website, we hope that our website will have multiple styles. users can choose different styles according to their own preferences. such styles can be changes in layout, differences in color, or it is a style specially customized for different user groups.
how can we achieve multi-style selection and real-time switching of styles?
in fact, ie does not support this function. we can leave it to the browser. firefox supports this function.
suppose we have two sets of css, enclosed in two different files: a.css and b.css. then add the following two lines of xhtml code between

and :
<link rel="stylesheet" type="text/css" title="主题a" href="a.css?7.1.34" /> 
<link rel="alternate stylesheet" type="text/css" title="主题b" href="b.css?7.1.34" />

then open this page with your firefox and select in the menu bar: view-> page style, it should you can see "theme a" and "theme b" and select them in real time.
another method we can use is to use dynamic programs, such as asp, php, jsp, etc. the advantages of this are direct, efficient, good compatibility, and the ability to remember user choices. the user's selection can be recorded in cookies or directly written to the database. when the user visits again, the style selected on the previous visit will be directly called. we won’t go into details about the specific production here. you can pay attention to our website www.52css.com. we will launch content in this area from time to time.
what method should we use now? the mainstream browser ie does not support the method of letting the browser choose. how to implement it with a program script? when my webpage is static, there is no database.
we can only choose to use javascript to get it done. let’s look at the following code:

function setactivestylesheet(title) { 
var i, a, main; 
for(i=0; (a = document.getelementsbytagname("link")[i]); i++) { 
if(a.getattribute("rel").indexof("style") != -1 && a.getattribute("title")) { 
a.disabled = true; 
if(a.getattribute("title") == title) a.disabled = false; 
} 
} 
} 
function getactivestylesheet() { 
var i, a; 
for(i=0; (a = document.getelementsbytagname("link")[i]); i++) { 
if(a.getattribute("rel").indexof("style") != -1 && a.getattribute("title") && !a.disabled) return a.getattribute("title"); 
} 
return null; 
} 
function getpreferredstylesheet() { 
var i, a; 
for(i=0; (a = document.getelementsbytagname("link")[i]); i++) { 
if(a.getattribute("rel").indexof("style") != -1 
&& a.getattribute("rel").indexof("alt") == -1 
&& a.getattribute("title") 
) return a.getattribute("title"); 
} 
return null; 
} 
function createcookie(name,value,days) { 
if (days) { 
var date = new date(); 
date.settime(date.gettime()+(days*24*60*60*1000)); 
var expires = "; expires="+date.togmtstring(); 
} 
else expires = ""; 
documents.cookie = name+"="+value+expires+"; path=/"; 
} 
function readcookie(name) { 
var nameeq = name + "="; 
var ca = documents.cookie.split(';'); 
for(var i=0;i < ca.length;i++) { 
var c = ca[i]; 
while (c.charat(0)==' ') c = c.substring(1,c.length); 
if (c.indexof(nameeq) == 0) return c.substring(nameeq.length,c.length); 
} 
return null; 
} 
window.onload = function(e) { 
var cookie = readcookie("style"); 
var title = cookie ? cookie : getpreferredstylesheet(); 
setactivestylesheet(title); 
} 
window.onunload = function(e) { 
var title = getactivestylesheet(); 
createcookie("style", title, 365); 
} 
var cookie = readcookie("style"); 
var title = cookie ? cookie : getpreferredstylesheet(); 
setactivestylesheet(title);

the above code is a javascript script that implements multi-style selection and real-time style switching. we can save the above code as a js file and display it on the required page. direct quote:

<script type="text/javascript" src="cssturn.js?7.1.34"></script>

of course, you can also write the above code directly inside the page.
we have three styles, one defaults to the other two styles. introduce these three css files into the page file:

<link rel="stylesheet" type="text/css" href="css.css?7.1.34" /> 
<link rel="stylesheet" type="text/css" href="aaa.css?7.1.34" title="aaa" /> 
<link rel="stylesheet" type="text/css" href="bbb.css?7.1.34" title="bbb" />

ok, we can now add a link to switch styles in the page:

<a href="#" onclick="setactivestylesheet('',1); return false;">默认样式-白色</a> 
<a href="#" onclick="setactivestylesheet('aaa',1); return false;">样式一-蓝色</a> 
<a href="#" onclick="setactivestylesheet('bbb',1); return false;">样式二-橙色</a>

now that we are done, let’s test our results above and see the effect.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "<a rel="nofollow" href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" target="_blank">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd</a>"> 
<html xmlns="<a rel="nofollow" href="http://www.w3.org/1999/xhtml" target="_blank">http://www.w3.org/1999/xhtml</a>"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<title>阿Q家园</title> 
<link rel="stylesheet"  type="text/CSS" href="<a rel="nofollow" href="http://www.52css.com/attachments/month_0701/r2007128164252.css?7.1.34" target="_blank">http://www.52css.com/attachments/month_0701/r2007128164252.css</a>"  /> 
<link rel="stylesheet" type="text/CSS" href="<a rel="nofollow" href="http://www.52css.com/attachments/month_0701/c2007128164223.css?7.1.34" target="_blank">http://www.52css.com/attachments/month_0701/c2007128164223.css</a>" title="aaa" /> 
<link rel="stylesheet" type="text/CSS" href="<a rel="nofollow" href="http://www.52css.com/attachments/month_0701/h2007128164239.css?7.1.34" target="_blank">http://www.52css.com/attachments/month_0701/h2007128164239.css</a>" title="bbb" /> 
<script type="text/javascript"> 
function setActiveStyleSheet(title) { 
  var i, a, main; 
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) { 
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) { 
      a.disabled = true; 
      if(a.getAttribute("title") == title) a.disabled = false; 
    } 
  } 
} 

function getActiveStyleSheet() { 
  var i, a; 
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) { 
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title"); 
  } 
  return null; 
} 

function getPreferredStyleSheet() { 
  var i, a; 
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) { 
    if(a.getAttribute("rel").indexOf("style") != -1 
       && a.getAttribute("rel").indexOf("alt") == -1 
       && a.getAttribute("title") 
       ) return a.getAttribute("title"); 
  } 
  return null; 
} 

function createCookie(name,value,days) { 
  if (days) { 
    var date = new Date(); 
    date.setTime(date.getTime()+(days*24*60*60*1000)); 
    var expires = "; expires="+date.toGMTString(); 
  } 
  else expires = ""; 
  documents.cookie = name+"="+value+expires+"; path=/"; 
} 

function readCookie(name) { 
  var nameEQ = name + "="; 
  var ca = documents.cookie.split(';'); 
  for(var i=0;i < ca.length;i++) { 
    var c = ca[i]; 
    while (c.charAt(0)==' ') c = c.substring(1,c.length); 
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); 
  } 
  return null; 
} 

window.onload = function(e) { 
  var cookie = readCookie("style"); 
  var title = cookie ? cookie : getPreferredStyleSheet(); 
  setActiveStyleSheet(title); 
} 

window.onunload = function(e) { 
  var title = getActiveStyleSheet(); 
  createCookie("style", title, 365); 
} 

var cookie = readCookie("style"); 
var title = cookie ? cookie : getPreferredStyleSheet(); 
setActiveStyleSheet(title); 
</script> 
</head> 
<body> 
<a href="#" onclick="setActiveStyleSheet('',1); return false;">默认样式-白色</a> 
<a href="#" onclick="setActiveStyleSheet('aaa',1); return false;">样式一-蓝色</a> 
<a href="#" onclick="setActiveStyleSheet('bbb',1); return false;">样式二-橙色</a> 
<p></p> 
</body> 
</html>


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)