Home Web Front-end JS Tutorial jQuery implements custom checkbox and radio styles_jquery

jQuery implements custom checkbox and radio styles_jquery

May 16, 2016 pm 03:50 PM
jquery

1, cause

Recently, I have to implement a customized radio style at work, and we usually use the default style. Because I really can’t think of a solution, I started searching, and finally I saw a good solution, which can perfectly solve our problem. problems encountered.

2, Principle

Everyone knows that when writing a structure, radio or checkbox will be used together with the label. When the for attribute value of the label is the same as the id value of the input, click the label to select the input. Here, the label is used to overwrite it. Our input default style is by adding a background image (beautified checkbox or radio) to the label, that is, during the click process, we cannot see the default input (set z-index:-1 for the input), and Click on the label, and load different background images through different events (here is the position of changing the background image)

3. Set the default style to beautify the checkbox or radio

(1) Page structure

<form class="form" method="post">
  <fieldset>
    <legend>Which genres do you like&#63;</legend>
    <input type="checkbox" value="action" id="check-1" name="genre"><label for="check-1" class="">Action / Adventure</label>
    <input type="checkbox" value="comedy" id="check-2" name="genre"><label for="check-2" class="">Comedy</label>
    <input type="checkbox" value="epic" id="check-3" name="genre"><label for="check-3" class="">Epic / Historical</label>
    <input type="checkbox" value="science" id="check-4" name="genre"><label for="check-4" class="">Science Fiction</label>
    <input type="checkbox" value="romance" id="check-5" name="genre"><label for="check-5" class="">Romance</label>
    <input type="checkbox" value="western" id="check-6" name="genre"><label for="check-6" class="">Western</label>
  </fieldset> 
  <fieldset>
    <legend>Caddyshack is the greatest movie of all time, right&#63;</legend>
    <input type="radio" value="1" id="radio-1" name="opinions"><label for="radio-1" class="">Totally</label>
    <input type="radio" value="1" id="radio-2" name="opinions"><label for="radio-2" class="">You must be kidding</label>
    <input type="radio" value="1" id="radio-3" name="opinions"><label for="radio-3" class="">What's Caddyshack&#63;</label>
  </fieldset>
</form>
Copy after login

(2) jquery code (the jquery library must be introduced)

jQuery.fn.customInput = function(){
  $(this).each(function(i){
    if($(this).is('[type=checkbox],[type=radio]')){
      var input = $(this);
      //get the associated label using the input's id
      var label = $('label[for='+input.attr('id')+']');
      //get type,for classname suffix
      var inputType = (input.is('[type=checkbox]')) &#63; 'checkbox' : 'radio';
      //wrap the input + label in a div
      $('<div class="custom-'+ inputType +'"></div>').insertBefore(input).append(input,label);
      //find all inputs in this set using the shared name attribute
      var allInputs = $('input[name='+input.attr('name')+']');
      //necessary for browsers that don't support the :hover pseudo class on labels
      label.hover(function(){
        $(this).addClass('hover');
        if(inputType == 'checkbox' && input.is(':checked')) {
          $(this).addClass('checkedHover');
        }
      },function(){
        $(this).removeClass('hover checkedHover');
      });
       
      //bind custom event, trigger it, bind click,focus,blur events
      input.bind('updateState',function(){
        if(input.is(':checked')){
          if(input.is(':radio')){
            allInputs.each(function(){
              $('label[for='+$(this).attr('id')+']').removeClass('checked');
            });
          };
          label.addClass('checked');
        } else {
          label.removeClass('checked checkedHover checkedFocus');
        }
      })
      .trigger('updateState')
      .click(function(){
        $(this).trigger('updateState');
      })
      .focus(function(){
        label.addClass('focus');
        if(inputType == 'checkbox' && input.is(':checked')) {
          $(this).addClass('checkedFocus');
        }
      })
      .blur(function(){
        label.removeClass('focus checkedFocus');
      });        
    }
  });
}
Copy after login

After introducing the jquery library and the above code, you can execute the following code

$('input').customInput();
Copy after login

(3) The generated outer div

If your code structure is that label and input are written in pairs, then a div will be generated outside them, as shown in the figure

(4) Set custom default style

Prepare a picture, as follows:

You may ask why the top is not at the top, but at a certain distance, because most of our input options are centered, and we use the background image of the label to simulate it, so we are trying to make the input options Display centered. In short: ico small icons must be arranged vertically, and a certain distance must be left to achieve centered display.

/* wrapper divs */
      .custom-checkbox,
      .custom-radio {
        position: relative;
        display: inline-block;
      }
      /* input, label positioning */
      .custom-checkbox input,
      .custom-radio input {
        position: absolute;
        left: 2px;
        top: 3px;
        margin: 0;
        z-index: -1;
      }
      .custom-checkbox label,
      .custom-radio label {
        display: block;
        position: relative;
        z-index: 1;
        font-size: 1.3em;
        padding-right: 1em;
        line-height: 1;
        padding: .5em 0 .5em 30px;
        margin: 0 0 .3em;
        cursor: pointer;
      }
Copy after login

These are the outermost settings, of course you can modify them yourself

/* ==默认状态效果== */
      .custom-checkbox label { 
        background: url(images/checkbox.gif) no-repeat; 
      }
      .custom-radio label { 
        background: url(images/button-radio.png) no-repeat; 
      }
      .custom-checkbox label, 
      .custom-radio label {
        background-position: 0px 0px;
      }

Copy after login
/*==鼠标悬停和得到焦点状态==*/
      .custom-checkbox label.hover,
      .custom-checkbox label.focus,
      .custom-radio label.hover,
      .custom-radio label.focus {
        /*background-position: -10px -114px;*/
      }
      
      /*==选中状态==*/
      .custom-checkbox label.checked,
      .custom-radio label.checked {
        background-position: 0px -47px;
      }
      .custom-checkbox label.checkedHover,
      .custom-checkbox label.checkedFocus {
        /*background-position: -10px -314px;*/
      }
      .custom-checkbox label.focus,
      .custom-radio label.focus {
        outline: 1px dotted #ccc;
      }

Copy after login

End: In short, I solved my problem perfectly, and I will send you a screenshot to see

The above is the entire content of this article, I hope you all like it.

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles