原码笔记

原码笔记

css单选按钮图标替换的方法

小诸哥 0

一.需求:替换单选按钮默认图标

二.原理:

  1.使用label扩大选择热区,隐藏input元素,

  2.添加一个元素设置其背景图作为默认显示的按钮图标并显示,

  3.为该元素添加一个伪元素相对于添加的元素绝对定位且默认不显示,在该伪元素中添加默认选中的背景图

  4.在input元素选中后,显示该伪元素,因为伪元素是绝对定位层级比较高所以会显示在上面,即选中的图标

三.HTML

  1. <label>
  2. <input name="price" type="radio" value="1" />
  3. <span className="show-radio"></span>
  4. <p>100-500</p>
  5. </label>

四.css

  1. input{
  2.  
  3.   display:none
  4.  
  5. };
  6.  
  7.     
  8.  
  9. .show-radio{
  10.   display: inline-block;
  11.   width:34px;
  12.   height:35px;
  13.   background:url('../../imgs/icons.png') no-repeat;
  14.   background-position:-529px -180px;
  15.   vertical-align: middle;
  16.   position: relative;
  17. }
  18. .show-radio:before{
  19.   content:'';
  20.   display: none;
  21.   width:34px;
  22.   height:35px;
  23.   background:url('../../imgs/icons.png') no-repeat;
  24.   background-position:-474px -180px;
  25.   vertical-align: middle;
  26.   position:absolute;
  27.   left:0;
  28.   top:0;
  29. }
  30. input:checked~show-radio:before{
  31.   display:block;
  32. }

五.效果

 

近重视实现思路和重要代码,部分省略,望见谅

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

标签: 单选按钮