chevron-left chevron-right

Piotr Nalepa Frontend, architecture and AI

[CSS][jQuery] Stylizacja dla elementów typu checkbox i radio

This version
blog.piotrnalepa.pl/2009/07/09/cssjquery-stylizacja-dla-elementow-typu-checkbox-i-radio
Published
Author
, Staff Software Engineer
Categories
CSS, JavaScript
Feedback
Write to me · Post on X

This post is 17 years old. Browsers and tools may have changed since then, so check the code against current documentation before you use it.

W dzisiejszej poradzie poruszam temat własnych stylów dla elementów strony WWW, które często służą do zaznaczania różnych opcji w ankietach czy sondażach, mowa o checkboxach i radiobuttonach. Dzięki tej poradzie będziecie mogli zastosować efektowne style dla swoich stron WWW.

Zaczynamy od kodu HTML, który wygląda nastepująco:

Example 1HTML
<input id="boks" type="checkbox" class="checkbox">
<label id="etykietka" for="boks" class="etykieta">Mój własny checkbox</label>

Jak widać kod HTML nie jest ani trochę skomplikowany.

Teraz pora na style, dzięki którym nasza strona nabierze efektowności:

Example 2CSS
.checkbox {
	display: none;
}
.etykieta {
	background: url("img/tak.png") no-repeat;
	padding-left: 35px;
	padding-top: 3px;
	margin: 5px;
	height: 28px;
	width: 150px;
	display: block;
}
.etykieta:hover {
	text-decoration: underline;
}
.etykieta_wybrana {
	background: url("img/nie.png") no-repeat;
}

A na sam koniec zamieszczam kod w JavaScript, dzięki któremu tworzy się magia na stronie:

Example 3JavaScript
$(document).ready(function(){
	$(".checkbox").change(function(){
		if($(this).is(":checked")){
			$(this).next("label").addClass("etykieta_wybrana");
		}else{
			$(this).next("label").removeClass("etykieta_wybrana");
		}
	});
});

Jednak by ten efekt zadziałał należy w sekcji "head" strony wstawić odnośnik do biblioteki jQuery:

Example 4HTML
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

To już wszystko. Demo z tego artykułu możecie zobaczyć tutaj.

Share
Feedback

About the author

Staff Software Engineer

I've been writing this blog since 2009 and building for the web professionally for 14 years. Today I lead the frontend of the Cosmos platform at Bishop Fox, where I've been since day one of the project. Before that I worked at OLX, KUDO, Auto1 and eZ Systems. Here I write about what I've learned in practice: JavaScript, TypeScript, React, CSS and frontend architecture. I've also spoken at conferences across Poland and Europe. Got a question or an idea for a post? Let me know!