Home>

In the process of creating a web page,Often you need to click to switch the background image.This article focuses on the implementation of checkbox background image switching in the form.As shown in the figure, after entering the user name and password,User needs to choose whether to remember password

The html source code is as follows:

<div>
 <input type="checkbox" checked="checked" /><label>remember password</label>
 </div>

The checkbox is checked by default.

Style,The css code is as follows:

.check {
  text-align:right;
  font-size:24px;
  height:50px;
  width:150px;
  background:url (img/btn_1.png) left center no-repeat;
  }
.checkbox {
  width:50px;
  height:50px;
  vertical-align:middle;
  filter:alpha (opacity=0);
  -moz-opacity:0;
  -khtml-opacity:0;
  opacity:0;
  }
label {
  vertical-align:middle;
  }

Set the checkbox transparency to 0, and replace the checkbox with a background image to get the effect with the checked image.The default is to check the password,btn_1.png is the check image with blue background.It is worth noting thatYou can add vertical-align:middle;attribute to both input label and label label to achieve vertical center alignment between text and checkbox.

Next, click to switch the background image of the checkbox.The toggle () method in jquery below 1.9 can directly switch:

toggle (objs) {
  $(objs) .each (function () {
   if ($(this) .is (":hidden")) $(this) .show ();else $(this) .hide ();
  });
 }

However, this method has been removed in jquery 1.9 and above.So it can be implemented with native javascript, the specific code is as follows:

$(document) .ready (function () {
 var flag=1;
 $(". check"). click (function () {
  if (flag == 1) {
   $(". check"). css ("background", "url (img/btn_1.png) left center no-repeat");
   flag=0;
  } else {
   $(". check"). css ("background", "url (img/btn_2.png) left center no-repeat");
   flag=1;
  }
 })
});
  • Previous Introduction to some basic operating methods of common multimedia files in Java
  • Next Graphics2D class basic usage tutorial in Java