Using JQuery / JS & Select Boxes to change the stylesheet depending on the selection
Using JQuery / JS & Select Boxes to change the stylesheet depending on the selection I want the user to be able to, say, select "Super Admin" from a drop down select box and have the div that contains the description of user level "Super admin" (located below the form) to change its
.superAdmin div {background-color: #000;}
I a开发者_JAVA百科ssume its some form of manipulation of the onChange();
handle.
Sorry if this questions is ridiculously low level, but I am a real beginner with JS, let along JQuery. +1 if you can also supply exactly how to implement the code (what to put in the <head></head>
tags)
Thanks in advance, Huge supporter of this site (90% of all the issues I run into have already been asked here, I just couldnt find anything on this...)
Say you have a CSS stylesheet with the definition of all the classes you may want to add:
.user {background-color: #F00;}
.admin {background-color: #0F0;}
.superAdmin {background-color: #00F;}
and you have the HTML for your select box:
<select id="css-changer">
<option></option>
<option value="user">User</option>
<option value="admin">Admin</option>
<option value="superAdmin">Super Admin</option>
</select>
and for your divs:
<div id="user">User div</div>
<div id="admin">Admin div</div>
<div id="superAdmin">Super Admin div</div>
Then your javascript with jQuery would be:
$(document).ready(function() {
$("#css-changer").change(function() {
var value = $(this).find("option:selected").val();
switch(value) {
case "user":
$("#user").addClass("user");
$("#admin,#superAdmin").removeClass(); // removes all classes
break;
case "admin":
$("#admin").addClass("admin");
$("#user,#superAdmin").removeClass(); // removes all classes
break;
case "superAdmin":
$("#superAdmin").addClass("superAdmin");
$("#user,#admin").removeClass(); // removes all classes
break;
}
});
});
You can see this working.
To get the JS and CSS in your page, create an external style sheet with the right definitions and include it as described by the spec with a tag like that below:
<link href="mystyle.css" rel="stylesheet" type="text/css">
and make sure to include jQuery and an external javascript file (to make things unobtrusive). To include them use HTML like that below:
<!-- jQuery goes first! -->
<script src="path/to/jQuery/CDN/jquery-min-1.5.1.js" type="text/javascript"></script>
<script src="myExternal.js" type="text/javascript"></script>
maybe
$("#div").change(function(){
$("#div1").css("color", "red");
})
精彩评论