鍍金池/ 問答/HTML/ 如何用【偽類】成功修改HTML checkbox默認樣式?(新checkbox覆

如何用【偽類】成功修改HTML checkbox默認樣式?(新checkbox覆蓋老checkbox無法點擊的問題)

按照一篇博客上的指導,修改checkbox默認樣式:
(博客地址: https://www.cnblogs.com/GumpY...

效果圖:圖片描述

按照博客,我的意圖是:
1-把原checkbox 的透明度設置0(透明)、z-index設為2(層級比自己畫的checkbox高)
2-用偽類自己制一個checkbox(這個簡單,邊線設置一下就行)
3-再用偽類(關聯(lián)原checkbox選中)做一個checkbox選中的狀態(tài)(有底色、有勾號)

OK,代碼如下:

input[type="checkbox"] {
    opacity: 0;
    z-index: 2;
}
label.chbox_label:before {
    content: '';
    position: absolute;
    top: 1px;
    left: -22px;
    width: 15px;
    height: 15px;
    border: 1px #DCDCDC solid;
    border-radius: 2px;
}
input[type="checkbox"]:checked+label:after {
    content: '';
    position: absolute;
    top: 1px;
    left: -22px;
    width: 15px;
    height: 15px;
    background: url("../yhe_resource/nike.png") no-repeat center  #00BEBE;
    border-radius: 2px;
}

但是.............
=======(以下是實際效果)========================
1-首先如我所愿,新checkbox蓋在老checkbox之上了; 但是,真的是“蓋上了”,我點不到老checkbox,導致選中的效果出不來
圖片描述

2-于是我只好console里把新checkbox移開,這下能點了!
圖片描述

3-然而,再次點擊選中的checkbox,并不會回到框框的狀態(tài)....

======================
求解 TT....

回答
編輯回答
司令

似乎很簡單, 可以在 這里體驗, 代碼如下:

HTML:

<input id="input-1" type="checkbox" name="input-1"/>
<label for="input-1">Label</label>

CSS:

input[type=checkbox] {
  position: relative;
  opacity: 0;
  z-index: 2;
  width: 18px;
  height: 18px;
  margin: 0;
  + label {
    position: relative;
    overflow: visible;
    padding-left: 6px;
    &:before, &:after {
      position: absolute;
      z-index: 1;
      top: 50%;
      left: -18px;
      height: 18px;
      width: 18px;
      margin-top: -9px;
      content: "";
      border: 1px solid #000;
      cursor: pointer;
    }
  }
  &:checked + label {
    &:after {
      content: "?";
      line-height: 18px;
      font-size: 16px;
      text-align: center;
    }
  }
}
2018年8月12日 23:08
編輯回答
遲月

感謝 @acrazing 。根據他的回答,我寫出了正確的代碼:

input[type="checkbox"] {
    position: relative;
    opacity: 0;
    transform: translateY(2px);
    z-index: 2;
    width: 15px;
    height: 15px;
}
input[type="checkbox"]+label { 
    font-weight: 400;
    padding-left: 6px;
}
input[type="checkbox"]+label:before { 
    content: "";
    position: absolute;
    z-index: 1;
    top: 1px;
    left: -22px;
    width: 15px;
    height: 15px;
    border: 1px #DCDCDC solid;
    border-radius: 2px;
    cursor: pointer;
}
input[type="checkbox"]:checked+label:after {
    content: "";
    position: absolute;
    top: 1px;
    left: -22px;
    width: 15px;
    height: 15px;
    background: url("../yhe_resource/nike.png") no-repeat center  #00BEBE;
    border-radius: 2px;
}

【一行代碼破案】
在 input[type="checkbox"] 中增加: position: relative

》 直接解決 老checkbox被遮蓋無法點擊
》 直接解決點擊后再次點擊無法取消選擇

另外,參考的原博 https://www.cnblogs.com/GumpY... 將checkbox設置為absolute,是錯誤的!

2018年9月12日 00:57